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.
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.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With