Search code examples
c#c++eventsclr

How will clr handle standard events in C# compared to c++ for windows controls?


How is c# handle a event under the hood in clr, for standard win32 controls, say a button:

Example: (c#)

    private void Form1_Load(object sender, EventArgs e)
    {
        button1.Click += (_, __) => { MessageBox.Show("You clicked me !"); };
    }

Is it like c++, in the main message loop?`

Example:

while (GetMessage(&msg, NULL, 0, 0))
{
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

switch (message)
{

case WM_COMMAND:


    if(hWnd>0 && hWnd==buttonhwnd) //Button click
    {
        callback_button();
    }

default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

I mean will all standard controls in c# send every signal, like click, mouse over, etc. to a simular loop - and then to callback registred in the source code? Like my lambda exemple?


Solution

  • Sure, the basic mechanism is the same. However, Winforms (and somewhat WPF) significantly alters the message routing. In Windows, a child control sends notifications to its parent window. The Winforms plumbing changes that by a mixture of window sub-classing and message reflecting to have code run in the control itself. A button's OnClick() method for example.

    From where, through event subscriptions, any other class can receive the Click event callback. A common pattern for example is not to have the panel on which you place a button process the callback but the upper level form. This buys a great deal of flexibility over the native Windows way.