Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Active Process Name in C#?

Tags:

c#

How to get active process name in C#?

I know that I must use this code:

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

but I don't know how use it.

like image 300
p.eon13 Avatar asked Jul 04 '11 09:07

p.eon13


People also ask

How can I get current process ID?

You can get the process ID of a process by calling getpid . The function getppid returns the process ID of the parent of the current process (this is also known as the parent process ID). Your program should include the header files unistd. h and sys/types.

How to check status of a process in Linux?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.


3 Answers

As mentioned in this answer, you have to use GetWindowThreadProcessId() to get the process id for the window and then you can use the 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 that this seems to throw an exception (“A 32 bit processes cannot access modules of a 64 bit process”) when run from a 32-bit application when the active process is 64-bit.

EDIT: As Damien pointed out, this code is prone to race conditions, because the process that had the active window at the time when GetForegroundWindow() was called might not exist anymore when GetWindowThreadProcessId() is called. Even worse situation would be if the same hwnd would be assigned to another window at that time, but I guess this should be really rare.

like image 198
svick Avatar answered Nov 01 '22 16:11

svick


I would suggest using System.Diagnostics.Process.

var currentProc = System.Diagnostics.Process.GetCurrentProcess();
string name = currentProc.ProcessName;

As an alternative you could use:

string name = currentProc.MainModule.FileName;
like image 21
Ostemar Avatar answered Nov 01 '22 18:11

Ostemar


Its just need two line of code, you can use linq to get all processes.

var processss = from proc in System.Diagnostics.Process.GetProcesses() orderby proc.ProcessName ascending select proc;
foreach (var item in processss) {
    Console.WriteLine(item.ProcessName );
}

Now you have all active process by just on line.

like image 3
khaled Dehia Avatar answered Nov 01 '22 17:11

khaled Dehia