如何在C#中获取消息?

Iva*_*nov 0 c# message winsock winforms

如何获取特定方法的特定消息?

我见过一些例子,人们使用"ref",但我不明白.

例如,在delphi中,我的函数(方法)必须在Main Form类中声明,并且在我必须放置消息的声明旁边

type
  TForm1 = class(TForm)
    ...
  protected
    procedure MessageHandler(var Msg:Tmessage);Message WM_WINSOCK_ASYNC_MSG;
end;
Run Code Online (Sandbox Code Playgroud)

我需要在C#中使用它,所以我可以在我的应用程序中使用WSAAsyncSelect

检查>我的其他问题<以赏金550的声望来理解我的意思

dom*_*mer 7

您可以在控件(例如表单)上覆盖WndProc方法.

WndProc接受对消息对象的引用.C#中的ref参数类似于Delphi中的var参数.消息对象具有包含消息类型的Msg属性,例如(来自MSDN):

protected override void WndProc(ref Message m) 
{
    // Listen for operating system messages.
    switch (m.Msg)
    {
        // The WM_ACTIVATEAPP message occurs when the application
        // becomes the active application or becomes inactive.
        case WM_ACTIVATEAPP:

            // The WParam value identifies what is occurring.
            appActive = (((int)m.WParam != 0));

            // Invalidate to get new text painted.
            this.Invalidate();

            break;                
    }        
    base.WndProc(ref m);
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

在.NET winforms中,所有消息都会转到WndProc,因此您可以覆盖:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_WINSOCK_ASYNC_MSG)
        {
            // invoke your method
        }
        else
        {
            base.WndProc(ref m);
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果我有误解,请说-但我认为你会做很好的避免这种低级的做法,并描述你想要什么来实现 -即它可能是.Invoke/ .BeginInvoke是比较合适的.