C# 有相当于 Delphi 的 message 关键字吗?
在delphi中,我可以像这样创建自己的消息,
const MY_MESSAGE = WM_USER+100;
procedure MyMessage(var Msg: TMessage); message MY_MESSAGE;
procedure TForm1.MyMessage(var Msg: TMessage);
begin
....
end;
但是在c#中我可以这样做
public static uint ms;
protected override void WndProc(ref Message m)
{
if(m.Msg == ms)
MessageBox.Show("example");
else
base.WndProc(ref m);
}
void Button1Click(object sender, EventArgs e)
{
PostMessage(HWND_BROADCAST,ms,IntPtr.Zero,IntPtr.Zero);
}
,但我不想重写WndProc(),我想创建我自己的MyMessage()函数,当我发布消息时它会运行。
我怎样才能做到这一点? 谢谢。
In delphi, I can create my own message like this,
const MY_MESSAGE = WM_USER+100;
procedure MyMessage(var Msg: TMessage); message MY_MESSAGE;
procedure TForm1.MyMessage(var Msg: TMessage);
begin
....
end;
bu in c# I can do that like this
public static uint ms;
protected override void WndProc(ref Message m)
{
if(m.Msg == ms)
MessageBox.Show("example");
else
base.WndProc(ref m);
}
void Button1Click(object sender, EventArgs e)
{
PostMessage(HWND_BROADCAST,ms,IntPtr.Zero,IntPtr.Zero);
}
but I don't want to override WndProc(), I want to create my own MyMessage() function, and when I post message it will run.
How can I do that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Delphi 的一个特殊功能,C# 中没有类似的功能。在 C# 中,您需要重写
WndProc()
。That's a special feature of Delphi of which there is no analogue in C#. In C# you need to override
WndProc()
.看起来非常相似的事情可以使用
.NET
反射和自定义属性来完成。我认为性能对于生产使用来说还可以,但不值得,因为这仍然需要重写 WndProc 来调用自定义调度程序,并且一旦 WndProc 就位,它需要一行代码来调用自定义调度程序,或者需要 3 行代码来编写正确的switch
语句。如果代码是从“基”类调用的,那么您继承它可能是值得的。以防万一您想知道,我这样做是因为我正在学习 C# + .NET 并且很好奇可以做什么。
一旦“管道”完成,代码将如下所示:
这是“管道”。更多的代码实现了识别所有 Windows 消息处理程序例程(基于自定义属性)的代码,并使用几个字典缓存所有这些结果(因此只需要完成繁重的工作)一次)。
Something that looks very similar can be done using
.NET
reflection and custom attributes. I think performance would be OK for production use, but not worth it since this still requires overridingWndProc
to call the custom dispatcher, and once theWndProc
is put into place, it takes one line of code to call the custom dispatcher OR 3 lines of code to write a properswitch
statement. If the code is called from a "base" class you then inherit from it might be worth it.Just in case you were wondering, I'm doing this because I'm lerarning C# + .NET and was curious what could be done.
Here's how the code would look like, once the "plumbing" is done:
And here's the "plumbing". A lot more code that implements the code to identify all windows message handler routines (based on custom attribute), and cache all those results using a couple of dictionaries (so the heavy-lifting only needs to be done once).