FindWindowEx 是 Windows API 中的一個函數,用于在 Windows 操作系統中查找特定的窗口句柄。它通常用于自動化任務、測試或與其他應用程序進行交互。在 C# 中,你可以使用 P/Invoke(平臺調用)來調用 FindWindowEx 函數。
以下是一個簡單的示例,展示了如何在 C# 中使用 FindWindowEx 函數查找一個窗口:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
static void Main()
{
// 查找一個窗口,其類名為 "Button",窗口名為 "OK"
IntPtr hwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Button", "OK");
if (hwnd != IntPtr.Zero)
{
Console.WriteLine("找到了窗口,句柄為: " + hwnd);
}
else
{
Console.WriteLine("未找到窗口");
}
}
}
在這個示例中,我們首先使用 DllImport 屬性導入 user32.dll 庫,并定義了 FindWindowEx 函數的簽名。然后,我們在 Main 方法中調用 FindWindowEx 函數,傳入父窗口句柄(IntPtr.Zero 表示頂層窗口)、子窗口句柄(IntPtr.Zero 表示第一個子窗口)、類名("Button")和窗口名("OK")。如果找到了匹配的窗口,函數將返回一個非空的句柄;否則,返回 IntPtr.Zero。