首先介紹基本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工具來查看窗口的句柄、標題、類型等信息,非常方便。