簡體   English   中英

如何獲取任務管理器中顯示的活動窗口應用程序名稱

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

我正在嘗試獲取活動窗口的名稱,如任務管理器應用程序列表中所示(使用 c#)。 我遇到了與此處所述相同的問題。 我試圖按照他們的描述去做,但是我遇到了問題,而重點應用程序是我得到異常的圖片庫。 我也試過這個,但沒有給我預期的結果。 現在我使用:

IntPtr handle = IntPtr.Zero;
handle = GetForegroundWindow();

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

並根據我為大多數常見應用程序創建的表刪除不相關的內容,但我不喜歡這種解決方法。 有沒有辦法獲取所有正在運行的應用程序的任務管理器中的應用程序名稱?

在閱讀了很多之后,我將我的代碼分為兩種情況,分別用於地鐵應用程序和所有其他應用程序。 我的解決方案處理了我為 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;
}

聽起來您需要遍歷每個頂級窗口(桌面窗口的直接子窗口,通過 pinvoke http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs. 85).aspx ),然后調用您的 GetWindowText pinvoke 函數。

EnumWindows 將“通過將句柄傳遞給每個窗口,依次傳遞給應用程序定義的回調函數,枚舉屏幕上的所有頂級窗口。”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM