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