C#在應(yīng)用程序間發(fā)送消息實(shí)現(xiàn)淺析
說來說去,還是覺得API的功能是最強(qiáng)大的,但是.NET FCL,MFC等對API的封裝之后也使得程序的開發(fā)變得更加容易。本模塊的主要原理還是使用API,查找指定類型,窗口文本的窗口對象,使用C#發(fā)送消息,獲取該對象的指針。然后實(shí)現(xiàn)C#應(yīng)用程序間使用C#發(fā)送消息操作該對象。
C#發(fā)送消息實(shí)例1:
創(chuàng)建一個(gè)C#Windows Form應(yīng)用程序,向窗口中添加一個(gè)按鈕button1,添加事件相應(yīng)函數(shù):
- private void button1_Click(object sender, System.EventArgs e)
- {
- MessageBox.Show("This is button1 click!");
- }
C#發(fā)送消息實(shí)例2:
創(chuàng)建一個(gè)C# Windows Form應(yīng)用程序,添加一個(gè)按鈕控件button1
1:C#在應(yīng)用程序添加using System.Runtime.InteropServices;
2:C#在應(yīng)用程序添加對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:C#在應(yīng)用程序添加button1的相應(yīng)函數(shù):
- private void button1_Click(object sender, System.EventArgs e)
- {
- IntPtr hwnd_win ; // 存放實(shí)例1中的Form1窗口的窗口句柄
- IntPtr hwnd_button ; // 存放實(shí)例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);
- }
總結(jié):
其實(shí)C#幕后還是采用的C#發(fā)送消息的處理機(jī)制,本創(chuàng)許也充分利用了Windows的消息處理機(jī)之。
附帶一個(gè)獲取窗口類型的技巧:使用SPY ++就可以獲取任何窗口的窗口類型。
所有的類似于WM_CHAR,WM_COMMAND等消息的值,可以在.Net目錄下的WinUser.h文件中查詢到。
【編輯推薦】