摘要:說來說去,還是覺得API的功能是最強大的,但是.NET FCL,MFC等對API的封裝之后也使得程序的開發(fā)變得更加容易。本模塊的主要原理還是使用API,查找指定類型,窗口文本的窗口對象,獲取該對象的指針。然后操作該對象。
實例1:
創(chuàng)建一個C#Windows Form應用程序,向窗口中添加一個按鈕button1,添加事件相應函數(shù):
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("This is button1 click!");
}
實例2:
創(chuàng)建一個C# Windows Form應用程序,添加一個按鈕控件button1
1:添加using System.Runtime.InteropServices;
2: 添加對API的引用:
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,IntPtr hwndChildAfter,string lpszClass,string lpszWindow);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr PostMessage(IntPtr hwnd,int wMsg,IntPtr wParam,IntPtr lParam);
3:添加button1的相應函數(shù):
private void button1_Click(object sender, System.EventArgs e)
{
IntPtr hwnd_win ; // 存放實例1中的Form1窗口的窗口句柄
IntPtr hwnd_button ; // 存放實例1中的Form1中的button1控件的窗口句柄
// 參數(shù)1:窗口類型,參數(shù)2:窗口名稱
hwnd_win = FindWindow("WindowsForms10.Window.8.app3", "Form1"); // 得到Form1窗口的句柄。
// 參數(shù)1:父窗口句柄, 參數(shù)2:子窗口指針;參數(shù)3:窗口類型;參數(shù)4:窗口文本
hwnd_button = FindWindowEx(hwnd_win ,new IntPtr(0) ,"WindowsForms10.BUTTON.app3","button1");
// 定義待發(fā)送的消息
const int BM_CLICK = 0x00F5;
Message msg = Message.Create(hwnd_button ,BM_CLICK ,new IntPtr(0),new IntPtr(0));
// 向Form1窗口的button1控件發(fā)送BM_CLICK消息
PostMessage(msg.HWnd ,msg.Msg ,msg.WParam ,msg.LParam);
}
總結:
其實C#幕后還是采用的消息處理機制,本創(chuàng)許也充分利用了Windows的消息處理機之。
附帶一個獲取窗口類型的技巧:使用SPY ++就可以獲取任何窗口的窗口類型。
所有的類似于WM_CHAR,WM_COMMAND等消息的值,可以在.Net目錄下的WinUser.h文件中查詢到。