C# 中如何定義和接收消息?
Wason
業余學習成果: 終于把自定義消息給搞定,好事多多分享!
在C#中目前我還沒有找到發送消息的類成員函數,所以只能采用通過調用WIN 32 API 的 SendMessage() 函數實現。由于 SendMessage的參數中需要得到窗體的句柄(handler) ,所以又要調用另一個API FindWindow(), 兩者配合使用,達到在不同窗體之間的消息發送和接收功能。
另外一個要點是,需要通過重寫(Override) 窗體的 DefWndProc() 過程來接收自定義的消息。DefWndProc 的重寫:
protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch(m.Msg) { case ...: break; default: base.DefWndProc(ref m); break; } }
下面是我的C#實踐例程。 ------------------------------------ ///////////////////////////////////////// ///file name: Note.cs /// public class Note { //聲明 API 函數
[DllImport("User32.dll",EntryPoint="SendMessage")] private static extern int SendMessage( int hWnd, // handle to destination window int Msg, // message int wParam, // first message parameter int lParam // second message parameter ); [DllImport("User32.dll",EntryPoint="FindWindow")] private static extern int FindWindow(string lpClassName,string lpWindowName); //定義消息常數 public const int USER = 0x500; public const int TEST = USER + 1;
//向窗體發送消息的函數
private void SendMsgToMainForm(int MSG) { int WINDOW_HANDLER = FindWindow(null,@"Note Pad"); if(WINDOW_HANDLER == 0) { throw new Exception("Could not find Main window!"); } SendMessage(WINDOW_HANDLER,MSG,100,200); } }
///////////////////////////////////////// /// File name : Form1.cs /// 接收消息的窗體 ///
public class Form1 : System.Windows.Forms.Form { public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// 重寫窗體的消息處理函數 protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch(m.Msg) { //接收自定義消息 USER,并顯示其參數 case Note.USER: string message = string.Format ("Received message! parameters are :{0},{1}",m.WParam ,m.LParam); MessageBox.Show (message); break; default: base.DefWndProc(ref m); break; } //Console.WriteLine(m.LParam); }
--
Wilson Wei
|