Get process

ZombineDev via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 5 11:58:44 PST 2016


On Tuesday, 5 January 2016 at 18:10:28 UTC, Bauss wrote:
> Oh yeah I forgot to notice that by name would be preferred. Not 
> title, but name.

I have adapted the answer on Stackoverflow [1] for D:

// These Windows headers require DMD >= v2.070
import core.sys.windows.winnt : PROCESS_QUERY_INFORMATION, 
PROCESS_VM_READ;
import core.sys.windows.winbase : OpenProcess, GetCurrentProcess;
import core.sys.windows.psapi : GetProcessImageFileNameW, 
GetModuleFileNameEx;

import std.stdio : writeln;

void main()
{
     // 1) Get a handle to the process

     // 1.1) Example - get current process:
     auto processHandle = GetCurrentProcess();

     // 1.2) Example - get process with id 8036:
     // auto processHandle = OpenProcess(
     //     PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
     //     FALSE,
     //     8036 /* This is the PID, you can find one from windows 
task manager */
     // );

     // 2) Allocate a buffer for the name
     wchar[2048] name;

     // 3.1) Call GetProcessImageFileNameW
     uint bytesWritten = GetProcessImageFileNameW(processHandle, 
name.ptr, name.length);

     // 3.2) or call  or GetModuleFileNameEx
     //uint bytesWritten = GetModuleFileNameEx(processHandle, 
null, name.ptr, name.length);

     assert (bytesWritten > 0, "Error: GetProcessImageFileName() 
wrote zero bytes!");

     writeln(name);
}

Please note that this is Windows only and you need to use DMD 
2.070 [2] or newer.
I'm not on Windows so I can't test it now, but this should be the 
basic idea.

[1]: 
http://stackoverflow.com/questions/4570174/how-to-get-the-process-name-in-c/4570225
[2]: http://forum.dlang.org/thread/n6bsnt$iuc$1@digitalmars.com


More information about the Digitalmars-d-learn mailing list