2009-12-17 38 views
4

如何以編程方式檢測某個線程是否具有針對給定進程的窗口句柄?如何檢測線程是否有窗口句柄?

間諜++給了我這個信息,但我需要通過編程來完成。

我需要在C#中執行此操作,但.net診斷庫不會提供此信息。我想象間諜++使用一些我不知道的Windows API調用。

我有權訪問我正在嘗試調試的系統的代碼。我想嵌入一些由定時器定期調用的代碼,它將檢測有多少個線程包含窗口句柄並記錄此信息。

感謝

回答

3

我相信你可以用WIN API函數:EnumWindowsProc通過窗口句柄迭代和GetWindowThreadProcessId讓與給定的窗口相關的線程ID和進程ID處理

請檢查下面的例子將爲您工作:

此代碼使用System.Diagnostics迭代進程和線程;對於我打電話GetWindowHandlesForThread功能每個線程ID(見下面的代碼)

foreach (Process procesInfo in Process.GetProcesses()) 
{ 
    Console.WriteLine("process {0} {1:x}", procesInfo.ProcessName, procesInfo.Id); 
    foreach (ProcessThread threadInfo in procesInfo.Threads) 
    { 
     Console.WriteLine("\tthread {0:x}", threadInfo.Id); 
     IntPtr[] windows = GetWindowHandlesForThread(threadInfo.Id); 
     if (windows != null && windows.Length > 0) 
      foreach (IntPtr hWnd in windows) 
       Console.WriteLine("\t\twindow {0:x}", hWnd.ToInt32()); 
    } 
} 

GetWindowHandlesForThread實現:代碼

private IntPtr[] GetWindowHandlesForThread(int threadHandle) 
{ 
    _results.Clear(); 
    EnumWindows(WindowEnum, threadHandle); 
    return _results.ToArray(); 
} 

private delegate int EnumWindowsProc(IntPtr hwnd, int lParam); 

[DllImport("user32.Dll")] 
private static extern int EnumWindows(EnumWindowsProc x, int y); 
[DllImport("user32.dll")] 
public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId); 

private List<IntPtr> _results = new List<IntPtr>(); 

private int WindowEnum(IntPtr hWnd, int lParam) 
{   
    int processID = 0; 
    int threadID = GetWindowThreadProcessId(hWnd, out processID); 
    if (threadID == lParam) _results.Add(hWnd); 
    return 1; 
} 

結果上面應該轉儲到控制檯水木清華這樣的:

... 
process chrome b70 
    thread b78 
     window 2d04c8 
     window 10354 
... 
    thread bf8 
    thread c04 
... 
+0

非常感謝!這正是我需要的。 – 2009-12-18 16:40:33