温馨提示×

C#使用EnumWindows的最佳实践

c#
小樊
112
2024-07-18 18:00:25
栏目: 编程语言

EnumWindows函数是用于枚举所有顶层窗口的Windows API函数。在C#中,可以通过P/Invoke来调用EnumWindows函数。以下是EnumWindows函数的最佳实践示例:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

class Program
{
    // 声明EnumWindows函数
    [DllImport("user32.dll")]
    private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

    // 定义EnumWindowsProc委托
    private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

    // 程序入口
    static void Main()
    {
        List<IntPtr> windows = new List<IntPtr>();

        // 调用EnumWindows函数,将窗口句柄添加到列表中
        EnumWindows((hWnd, lParam) =>
        {
            windows.Add(hWnd);
            return true;
        }, IntPtr.Zero);

        // 输出窗口句柄
        foreach (IntPtr hWnd in windows)
        {
            Console.WriteLine(hWnd);
        }
    }
}

在上面的示例中,我们首先声明了EnumWindows函数,并定义了一个EnumWindowsProc委托用于处理每个枚举到的窗口。然后在Main方法中调用EnumWindows函数,将枚举到的窗口句柄添加到一个列表中,并输出每个窗口句柄。

需要注意的是,在调用EnumWindows函数时,需要传入一个委托作为参数,该委托的返回值决定是否继续枚举下一个窗口。在上面的示例中,我们始终返回true,表示继续枚举下一个窗口。根据具体需求,可以根据窗口的特征来筛选出感兴趣的窗口。

0