当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在C#中确定当前关注进程的名称》经验,为你挑选了1个好方法。

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



1> Ozgur Ozcita..:

我假设你想获得拥有当前焦点窗口的进程的名称.使用一些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";
}


小型优化:`Process p = Process.GetProcessById((int)pid);`
推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有