2010-01-08 137 views
5

我有一個應用程序,我想在後臺運行。我想獲取可執行文件的名稱,例如IExplorer.exe。我玩過以下代碼:C#獲取有關當前活動窗口的信息

[DllImport("user32.dll")] 
private static extern IntPtr GetForegroundWindow(); 

[DllImport("user32.dll")] 
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); 

public static void Main() 
{ 
    int chars = 256; 
    StringBuilder buff = new StringBuilder(chars); 
    while (true) 
    { 
     // Obtain the handle of the active window. 
     IntPtr handle = GetForegroundWindow(); 

     // Update the controls. 
     if (GetWindowText(handle, buff, chars) > 0) 
     { 
      Console.WriteLine(buff.ToString()); 
      Console.WriteLine(handle.ToString()); 
     } 
     Thread.Sleep(1000); 
    } 
} 

這隻會讓我看到窗口標題和句柄ID。我想獲得可執行文件的名稱(也許更多的信息)。

我該如何做到這一點?

+0

看這個問題的計算器上的最後一個答案: http://stackoverflow.com/questions/7268302/get-the-titles-of-all-open-windows/31517889#31517889 – Godvicien 2015-07-20 13:44:30

回答

7

我想你想「GetWindowModuleFileName()」,而不是GetWindowText時 您通過在HWND,所以你仍然需要調用GetForegroundWindow()

+0

鈣我使用事件來獲得屏幕標題,即當用戶改變屏幕焦點時,它應該觸發@ – CodeIt 2016-05-23 21:55:56

2

快速谷歌搜索帶來了這樣一個例子C-Sharpcorner article

+2

雖然此鏈接可能回答這個問題,最好在這裏包含答案的基本部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Joel 2014-02-19 12:25:35

相關問題