How to get active window app name as shown in task manager

前端 未结 2 1909
傲寒
傲寒 2021-01-06 09:37

I am trying to get the active window\'s name as shown in the task manager app list (using c#). I had the same issue as described here. I tried to do as they described but I

相关标签:
2条回答
  • 2021-01-06 10:06

    It sounds like you need to go through each top level window (direct children of the desktop window, use EnumWindows via pinvoke http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs.85).aspx) and then call your GetWindowText pinvoke function.

    EnumWindows will 'Enumerates all top-level windows on the screen by passing the handle to each window, in turn, to an application-defined callback function.'

    0 讨论(0)
  • 2021-01-06 10:07

    After reading a lot, I separated my code into two cases, for metro application and all other applications. My solution handle the exception I got for metro applications and exceptions I got regarding the platform. This is the code that finally worked:

    [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;
    }
    
    0 讨论(0)
提交回复
热议问题