主要使用了Windows API 实现,你可以在你C盘下的system32文件夹中找到user32.dll,函数的说明在MSDN都有,只需要拿名字去搜一下就行
根据窗口的类名和窗口名称获取窗口句柄,成功返回一个窗口的句柄,否则返回0:
[DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
在窗口列表中寻找与指定条件相符的第一个子窗口
[DllImport("user32.dll", EntryPoint = "FindWindowEx")] static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpClass, string lpszWindow);
找到句柄后向窗口发送消息,SendMessage方法有很多的重载
[DllImport("user32.dll ", EntryPoint = "SendMessage")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam); [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
const int WM_CHAR = 0x0102; const int WM_SETTEXT = 0x000C; const int VK_RETURN = 0x0d; static void Main(string[] args) { IntPtr handle = FindWindow(null, "Hello.txt - 记事本"); handle = FindWindowEx(handle, IntPtr.Zero, "Edit", null); if (handle == IntPtr.Zero) { Console.WriteLine("没有找到句柄"); return; } SendMessage(handle, WM_SETTEXT, IntPtr.Zero, "Hello word!");
SendMessage(handle, WM_CHAR, (IntPtr)VK_RETURN, IntPtr.Zero);//Enter
}
相关链接: