首页 > 开发 > 综合 > 正文

C#中使用SendMessage2

2020-02-03 13:45:36
字体:
来源:转载
供稿:网友
在c#中,程序采用了的驱动采用了事件驱动而不是原来的消息驱动,虽然.net框架提供的事件已经十分丰富,但是在以前的系统中定义了丰富的消息对系统的编程提供了方便的实现方法,因此在c#中使用消息有时候还是大大提高编程的效率的。
 1 定义消息
 
  在c#中消息需要定义成windows系统中的原始的16进制数字,比如
 
  const int wm_lbutton = 0x201; //定义了鼠标的左键点击消息
 
   public const int user = 0x0400 // 是windows系统定义的用户消息
 
 2 消息发送
 
  消息发送是通过windows提供的api函数sendmessage来实现的它的原型定义为
 
 [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
    );
 
3 消息的接受
 
 在c#中,任何一个窗口都有也消息的接收处理函数,就是defproc函数
 
你可以在form中重载该函数来处理消息
 
protected override void defwndproc ( ref system.winforms.message m )
{
switch(m.msg)
{
case wm_lbutton :
 ///string与mfc中的cstring的format函数的使用方法有所不同
 string message = string.format("收到消息!参数为:{0},{1}",m.wparam,m.lparam);
 messagebox.show(message);///显示一个消息框
 break;
default:
 base.defwndproc(ref m);///调用基类函数处理非自定义消息。
 break;
}
}
其实,c#中的事件也是通过封装系统消息来实现的,如果你在defwndproc函数中不处理该
那么,他会交给系统来处理该消息,系统便会通过代理来实现鼠标单击的处理函数,因此你可以通过
defproc函数来拦截消息,比如你想拦截某个按钮的单击消息
 
4 c#中其他的消息处理方法
  在c#中有的时候需要对控件的消息进行预处理,比如你用owc的spreedsheet控件来处理excel文件,你不想让用户可以随便选中
数据进行编辑,你就可以屏蔽掉鼠标事件,这个时候就必须拦截系统预先定义好的事件(这在mfc中称为子类化),你可以通过c#提供的一个接口
imessagefilter来实现消息的过滤
public class form1: system.windows.forms.form,imessagefilter
{
 const int wm_mousemove = 0x200
 public bool prefiltermessage(ref message m) 
 {  keys keycode = (keys)(int)m.wparam & keys.keycode; 
   if(m.msg == m.msg==wm_mousemove) //||m.msg == wm_lbuttondown
   {
    //messagebox.show("ignoring escape...");  
    return true; 
   } 
    return false; 
 }
}
注册会员,创建你的web开发资料库,
上一篇:C#程序调用外部程序

下一篇:C#鼠标位置

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表