Ivan Prodanov
Ivan Prodanov

Reputation: 35522

How can i get messages in C#?

How can I get a specific message on a specific method?

I've seen some examples and people use "ref" ,but I dont understand it.

In delphi,for example,my function(method) must be declared in the Main Form class and next to the declaration I have to put the message

type
  TForm1 = class(TForm)
    ...
  protected
    procedure MessageHandler(var Msg:Tmessage);Message WM_WINSOCK_ASYNC_MSG;
end;

I need this in C# so I can use WSAAsyncSelect in my application

Check >my other Question< with bounty 550 reputation to understand what I mean

Upvotes: 0

Views: 6242

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063338

In .NET winforms, all messages go to WndProc, so you can override that:

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

If I have misunderstood, please say - but I think you would do well to avoid this low-level approach, and describe what you want to achieve - i.e. it might be that .Invoke/.BeginInvoke are more appropriate.

Upvotes: 5

dommer
dommer

Reputation: 19820

You can override the WndProc method on a control (e.g. form).

WndProc takes a reference to a message object. A ref parameter in C# is akin to a var parameter in Delphi. The message object has a Msg property that contains the message type, e.g (from 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);
}

Upvotes: 7

Related Questions