溫馨提示×

C#使用EnumWindows的最佳實踐

c#
小樊
199
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女