首先介绍基本WindowsApi:
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
函数说明:在窗口列表中寻找与指定条件相符的第一个窗口
public static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
函数说明:在窗口列表中寻找与指定条件相符的第一个子窗口
用到的WindowApi类
static class WindowsApi
{
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
public static extern void SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hWndParent, CallBack lpfn, int lParam);
public delegate bool CallBack(IntPtr hwnd, int lParam);
}
class Program
{
/// <summary>
/// 查找窗体上控件句柄
/// </summary>
/// <param name="hwnd">父窗体句柄</param>
/// <param name="lpszWindow">控件标题(Text)</param>
/// <param name="bChild">设定是否在子窗体中查找</param>
/// <returns>控件句柄,没找到返回IntPtr.Zero</returns>
private IntPtr FindWindowEx(IntPtr hwnd, string lpszWindow, bool bChild)
{
IntPtr iResult = IntPtr.Zero;
// 首先在父窗体上查找控件
iResult = WindowsApi.FindWindowEx(hwnd, 0, null, lpszWindow);
// 如果找到直接返回控件句柄
if (iResult != IntPtr.Zero) return iResult;
// 如果设定了不在子窗体中查找
if (!bChild) return iResult;
// 枚举子窗体,查找控件句柄
int i = WindowsApi.EnumChildWindows(
hwnd,
(h, l) =>
{
IntPtr f1 = WindowsApi.FindWindowEx(h, 0, null, lpszWindow);
if (f1 == IntPtr.Zero)
return true;
else
{
iResult = f1;
return false;
}
},
0);
// 返回查找结果
return iResult;
}
private void OnRunClick(object sender, EventArgs e)
{
// 查找主界面句柄
IntPtr mainHandle = WindowsApi.FindWindow(null, "主界面(Ver:3.1.3.47)");
if (mainHandle != IntPtr.Zero)
{
// 查找按钮句柄
IntPtr iBt = FindWindowEx(mainHandle, "现(F1)", true);
if (iBt != IntPtr.Zero)
// 发送单击消息
WindowsApi.SendMessage(iBt, 0xF5, 0, 0);
}
}
}
应用工具:
这里可以应用spy工具来查看窗口的句柄、标题、类型等信息,非常方便。