如何在C#中获取活动进程名称?

p.e*_*n13 14 c#

如何在C#中获取活动进程名称?

我知道我必须使用这段代码:

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
Run Code Online (Sandbox Code Playgroud)

但我不知道怎么用它.

svi*_*ick 21

如本回答所述,您必须使用GetWindowThreadProcessId()获取窗口的进程ID,然后您可以使用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();
}
Run Code Online (Sandbox Code Playgroud)

请注意,当活动进程为64位时,从32位应用程序运行时,这似乎会引发异常("32位进程无法访问64位进程的模块").

编辑:正如Damien指出的那样,这段代码很容易出现竞争条件,因为GetForegroundWindow()调用时调用时具有活动窗口的进程可能不再存在GetWindowThreadProcessId().更糟糕的情况是,如果当时将相同的hwnd分配给另一个窗口,但我想这应该是非常罕见的.

  • 使用 ``p.processName`` 插入 ``p.MainModule.FileName`` 避免 32-64 位无法访问错误 (2认同)

Ost*_*mar 7

我建议使用System.Diagnostics.Process.

var currentProc = System.Diagnostics.Process.GetCurrentProcess();
string name = currentProc.ProcessName;
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以使用:

string name = currentProc.MainModule.FileName;
Run Code Online (Sandbox Code Playgroud)

  • 因为他提到了`GetForegroundWindow()`,我认为他想要当前活动窗口的进程,而不是当前进程. (7认同)