在C#中使用FindWindowEx函數,需要引入WindowsAPI的頭文件和函數聲明:
using System;
using System.Runtime.InteropServices;
public class WindowsAPI
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, out string lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetClassName(IntPtr hWnd, out string lpClassName, int nMaxCount);
}
public class Program
{
public static void Main()
{
string windowTitle = "Window Title";
IntPtr mainHWND = WindowsAPI.FindWindow(null, windowTitle);
if (mainHWND != IntPtr.Zero)
{
IntPtr childHWND = WindowsAPI.FindWindowEx(mainHWND, IntPtr.Zero, null, null);
if (childHWND != IntPtr.Zero)
{
string className;
WindowsAPI.GetClassName(childHWND, out className, 256);
string windowText;
WindowsAPI.GetWindowText(childHWND, out windowText, 256);
Console.WriteLine("Child HWND: " + childHWND.ToString());
Console.WriteLine("Class Name: " + className);
Console.WriteLine("Window Text: " + windowText);
}
else
{
Console.WriteLine("Child HWND not found.");
}
}
else
{
Console.WriteLine("Main HWND not found.");
}
}
}
在上述代碼中,首先通過FindWindow
函數查找到指定標題的主窗口句柄mainHWND
,然后通過FindWindowEx
函數在主窗口下查找子窗口句柄childHWND
。最后通過GetClassName
和GetWindowText
函數獲取子窗口的類名和窗口文本,并輸出到控制臺上。請注意,FindWindow
和FindWindowEx
函數的第一個參數lpClassName
可以指定窗口類名,如果為null
則表示忽略類名,只根據窗口標題查找。