我如何获得当前关注的应用程序名称

Jam*_*ran 0 c# winforms

我正在使用Windows窗体,并想知道用户是否可以获得其他应用程序的名称,是否有所关注.例如,如果我运行一个应用程序,那么我应该得到最近开始并且目前正在关注的应用程序的名称.我在谷歌搜索,但没有找到任何适当的解决方案.

谢谢!

小智 5

[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;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!你能解释一下`GetForegroundWindow();`方法和类`ManagementObjectSearcher`吗? (2认同)