主要使用了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
}
相關鏈接:
虛擬鍵表:http://baike.baidu.com/view/555571.htm
SendMessage消息類型:http://baike.baidu.com/view/1080187.htm