欢迎光临
我们一直在努力

C# 中如何定义和接收消息?-.NET教程,C#语言

建站超值云服务器,限时71元/月

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » C# 中如何定义和接收消息?-.NET教程,C#语言
分享到: 更多 (0)

相关推荐

  • 暂无文章