如何在C#中确定当前关注进程的名称

前端之家收集整理的这篇文章主要介绍了如何在C#中确定当前关注进程的名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,如果用户当前正在运行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";
}
原文链接:https://www.f2er.com/csharp/92503.html

猜你在找的C#相关文章