温馨提示×

C#中怎么使用FindWindowEx函数

c#
小亿
168
2023-08-03 12:01:21
栏目: 编程语言

在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。最后通过GetClassNameGetWindowText函数获取子窗口的类名和窗口文本,并输出到控制台上。请注意,FindWindowFindWindowEx函数的第一个参数lpClassName可以指定窗口类名,如果为null则表示忽略类名,只根据窗口标题查找。

0