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

时间:2016-05-04 21:56:49

标签: c# winforms

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

谢谢!

1 个答案:

答案 0 :(得分: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;
}