C#中使用SendMessage

在 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;

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus