在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
则表示忽略类名,只根据窗口标题查找。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#字典底层实现的原理是什么