How to Get Active Process Name in C#? -
how active process name in c#?
i know must use code:
[dllimport("user32.dll")] private static extern intptr getforegroundwindow(); but don't know how use it.
as mentioned in this answer, have use getwindowthreadprocessid() process id window , can use process:
[dllimport("user32.dll")] public static extern intptr getwindowthreadprocessid(intptr hwnd, out uint processid); [dllimport("user32.dll")] private static extern intptr getforegroundwindow(); string getactiveprocessfilename() { intptr hwnd = getforegroundwindow(); uint pid; getwindowthreadprocessid(hwnd, out pid); process p = process.getprocessbyid((int)pid); p.mainmodule.filename.dump(); } be aware seems throw exception (“a 32 bit processes cannot access modules of 64 bit process”) when run 32-bit application when active process 64-bit.
edit: damien pointed out, code prone race conditions, because process had active window @ time when getforegroundwindow() called might not exist anymore when getwindowthreadprocessid() called. worse situation if same hwnd assigned window @ time, guess should rare.
Comments
Post a Comment