C#中如何定义和接收消息

在C#中目前我还没有找到发送消息的类成员函数,所以只能采用通过调用WIN 32 API 的 SendMessage() 函数实现。由于 SendMessage的参数中需要得到窗体的句柄(handler) ,所以又要调用另一个API FindWindow(), 两者配合使用,达到在不同窗体之间的消息发送和接收功能。

另外一个要点是,需要通过重写(Override) 窗体的 DefWndProc() 过程来接收自定义的消息。DefWndProc 的重写:

 

 

  1. protected override void DefWndProc(ref System.Windows.Forms.Message m)    
  2. {    
  3. switch(m.Msg)    
  4. {    
  5. case ...:    
  6. break;    
  7. default:    
  8. base.DefWndProc(ref m);    
  9. break;    
  10. }    
  11. }   

 

下面是我的C#实践例程。

 

  1. /////////////////////////////////////////    
  2. ///file name: Note.cs    
  3. ///    
  4. public class Note    
  5. {    
  6.  //声明 API 函数    
  7.  [DllImport("User32.dll",EntryPoint="SendMessage")]    
  8.  private static extern int SendMessage(    
  9.  int hWnd, // handle to destination window    
  10.  int Msg, // message    
  11.  int wParam, // first message parameter    
  12.  int lParam // second message parameter    
  13.  );    
  14.  [DllImport("User32.dll",EntryPoint="FindWindow")]    
  15.  private static extern int FindWindow(string lpClassName,string    
  16. lpWindowName);    
  17.  //定义消息常数    
  18.  public const int USER = 0x500;    
  19.  public const int TEST = USER + 1;    
  20.  //向窗体发送消息的函数    
  21.  private void SendMsgToMainForm(int MSG)    
  22.  {    
  23.  int WINDOW_HANDLER = FindWindow(null,@"Note Pad");    
  24.  if(WINDOW_HANDLER == 0)    
  25.  {    
  26.  throw new Exception("Could not find Main window!");    
  27.  }    
  28.  SendMessage(WINDOW_HANDLER,MSG,100,200);    
  29.  }    
  30. }    
  31. /////////////////////////////////////////    
  32. /// File name : Form1.cs    
  33. /// 接收消息的窗体    
  34. ///    
  35. public class Form1 : System.Windows.Forms.Form    
  36. {    
  37.  public Form1()    
  38.  {    
  39.  //    
  40.  // Required for Windows Form Designer support    
  41.  //    
  42.  InitializeComponent();    
  43.  //    
  44.  // TODO: Add any constructor code after InitializeComponent call    
  45.  //    
  46.  }    
  47.  /// 重写窗体的消息处理函数    
  48.  protected override void DefWndProc(ref System.Windows.Forms.Message m)    
  49.  {    
  50.  switch(m.Msg)    
  51.  {    
  52.  //接收自定义消息 USER,并显示其参数    
  53.  case Note.USER:    
  54.  string message = string.Format ("Received message!    
  55. parameters are :{0},{1}",m.WParam ,m.LParam);    
  56.  MessageBox.Show (message);    
  57.  break;    
  58.  default:    
  59.  base.DefWndProc(ref m);    
  60.  break;    
  61.  }    
  62.  //Console.WriteLine(m.LParam);    
  63.  }   
posted @ 2009-05-23 21:01  起源  阅读(731)  评论(0)    收藏  举报