【问题标题】:How can I detect if a thread has windows handles?如何检测线程是否具有 Windows 句柄?
【发布时间】:2010-12-27 17:40:16
【问题描述】:

如何以编程方式检测线程是否具有给定进程的窗口句柄?

spy++ 为我提供了这些信息,但我需要以编程方式进行。

我需要在 C# 中执行此操作,但是 .net 诊断库不提供此信息。我想 spy++ 正在使用一些我不知道的 windows api 调用。

我可以访问我正在尝试调试的系统的代码。我想嵌入一些由计时器定期调用的代码,该代码将检测有多少线程包含窗口句柄并记录此信息。

谢谢

【问题讨论】:

    标签: c# windows multithreading gdi spy++


    【解决方案1】:

    我相信你可以使用win api函数:EnumWindowsProc遍历窗口句柄和GetWindowThreadProcessId获取与给定窗口句柄关联的线程ID和进程ID

    请检查以下示例是否适合您:

    此代码使用 System.Diagnostics 遍历进程和线程;对于每个线程 ID,我正在调用 GetWindowHandlesForThread 函数(参见下面的代码)

    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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2012-11-13
      • 2013-04-07
      相关资源
      最近更新 更多