代码之家  ›  专栏  ›  技术社区  ›  eskadi

如何获取任务管理器中显示的活动窗口应用程序名称

  •  6
  • eskadi  · 技术社区  · 12 年前

    我正在尝试获取任务管理器应用程序列表中显示的活动窗口的名称(使用c#)。 我遇到了与描述相同的问题 here . 我试图按照他们描述的那样做,但我遇到了问题,而重点应用程序是图片库,我例外。 我也试过了 this ,但没有什么能给我我期望的结果。 现在我使用:

    IntPtr handle = IntPtr.Zero;
    handle = GetForegroundWindow();
    
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    if (GetWindowText(handle, Buff, nChars) > 0)
    {
        windowText = Buff.ToString();
    }
    

    并根据我为大多数常用应用程序创建的表删除不相关的内容,但我不喜欢这种变通方法。 是否有方法获取所有正在运行的应用程序的任务管理器中的应用程序名称?

    2 回复  |  直到 9 年前
        1
  •  4
  •   eskadi    12 年前

    在阅读了很多之后,我将代码分为两种情况,分别用于metro应用程序和所有其他应用程序。 我的解决方案处理了地铁应用程序的异常和平台的异常。 这是最终有效的代码:

    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    
    [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    
    public string GetActiveWindowTitle()
    {
        var handle = GetForegroundWindow();
        string fileName = "";
        string name = "";
        uint pid = 0;
        GetWindowThreadProcessId(handle, out pid);
    
        Process p = Process.GetProcessById((int)pid);
        var processname = p.ProcessName;
    
        switch (processname)
        {
            case "explorer": //metro processes
            case "WWAHost":
                name = GetTitle(handle);
                return name;
            default:
                break;
        }
        string wmiQuery = string.Format("SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId LIKE '{0}'", pid.ToString());
        var pro = new ManagementObjectSearcher(wmiQuery).Get().Cast<ManagementObject>().FirstOrDefault();
        fileName = (string)pro["ExecutablePath"];
        // Get the file version
        FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
        // Get the file description
        name = myFileVersionInfo.FileDescription;
        if (name == "")
            name = GetTitle(handle);
    
     return name;
    }
    
    public string GetTitle(IntPtr handle)
    {
    string windowText = "";
        const int nChars = 256;
        StringBuilder Buff = new StringBuilder(nChars);
        if (GetWindowText(handle, Buff, nChars) > 0)
        {
            windowText = Buff.ToString();
        }
        return windowText;
    }
    
        2
  •  0
  •   Mike Cheel    12 年前

    听起来,您需要遍历每个顶级窗口(桌面窗口的直接子窗口,通过pinvoke使用EnumWindows http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs.85).aspx )然后调用GetWindowText pinvoke函数。

    EnumWindows将“通过将句柄传递给每个窗口,进而传递给应用程序定义的回调函数,枚举屏幕上的所有顶级窗口。”

    推荐文章