Is there a way to work with processes in Windows without extern(c)?

Dennis dkorpel at gmail.com
Wed Jan 13 15:11:40 UTC 2021


On Wednesday, 13 January 2021 at 14:04:52 UTC, dog2002 wrote:
> I could use extern(c) and Process Walking (Process32First, 
> Process32Next), but maybe there is a way to get the list by 
> means of D?

I don't think this is part of the standard library.
Here's a piece of code I wrote a while ago if that's useful:

```
pragma(lib, "Kernel32.lib");

/**
  * Get a list of tuples for each currently running process, 
containing name and id
  * Returns:
  *   array of (name, id) tuples
  */
auto getProcessList() @system {
	import core.sys.windows.tlhelp32: CreateToolhelp32Snapshot, 
TH32CS_SNAPPROCESS,
		Process32First, Process32Next, PROCESSENTRY32;
	import core.sys.windows.windows: HANDLE, INVALID_HANDLE_VALUE, 
CloseHandle;

	import std.typecons: Tuple, tuple;
	import std.string: fromStringz;
	import std.conv: to;

	HANDLE hProcessSnap;
	PROCESSENTRY32 pe32;
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	scope(exit) CloseHandle(hProcessSnap);

	alias restype = Tuple!(string, "name", int, "id");
	restype[] result = [];

	if (hProcessSnap != INVALID_HANDLE_VALUE) {
		pe32.dwSize = PROCESSENTRY32.sizeof;
		for (auto notAtEnd = Process32First(hProcessSnap, &pe32);
			notAtEnd;
			notAtEnd = Process32Next(hProcessSnap, &pe32)
		) {
			string processName = 
pe32.szExeFile[].ptr.fromStringz.to!string;
			result ~= restype(processName, pe32.th32ProcessID);
		}
	}

	return result;
}
```


More information about the Digitalmars-d-learn mailing list