加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:11:33 所属栏目:百科 来源:网络整理
导读:例如,如果用户当前正在运行VS2008,那么我想要值VS2008. 解决方法 我假设你想获得拥有当前焦点窗口的进程的名称.使用一些P / Invoke: // The GetForegroundWindow function returns a handle to the foreground window// (the window with which the user is
例如,如果用户当前正在运行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";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读