gpt4 book ai didi

c# - 如何确定 C# 中当前聚焦进程的名称

转载 作者:太空狗 更新时间:2023-10-29 18:21:27 25 4
gpt4 key购买 nike

例如,如果用户当前正在运行 VS2008,那么我需要值 VS2008。

最佳答案

我假设您想获取拥有当前焦点窗口的进程的名称。使用一些 P/Invoke:

// The GetForegroundWindow function returns a handle to the foreground window
// (the window with which the user is currently working).
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

// The GetWindowThreadProcessId function retrieves the identifier of the thread
// that created the specified window and, optionally, the identifier of the
// process that created the window.
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

// Returns the name of the process owning the foreground window.
private string GetForegroundProcessName()
{
IntPtr hwnd = GetForegroundWindow();

// The foreground window can be NULL in certain circumstances,
// such as when a window is losing activation.
if (hwnd == null)
return "Unknown";

uint pid;
GetWindowThreadProcessId(hwnd, out pid);

foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.Id == pid)
return p.ProcessName;
}

return "Unknown";
}

关于c# - 如何确定 C# 中当前聚焦进程的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/97283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com