Search code examples
c#c++windows-messages

PostMessage to hidden form doesn't work the first time


I have a C# WinForms application that appears in the system tray. The application is hiding the main form on load:

private void MainForm_Load(object sender, System.EventArgs e)
{
    Hide();
}

For the same main form, I've overriden the WndProc to catch a custom window message (that message is registered to Windows with the RegisterWindowMessage Win32 API call).

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_MYCUSTOM_MESSAGE)
    {
        // Handle custom message
    }
}

From an external C++ application I'm broadcasting the same custom window message with PostMessage.

UINT msg = RegisterWindowMessage(L"WM_MYCUSTOM_MESSAGE");
PostMessage(HWND_BROADCAST, msg, NULL, NULL);

When I execute the above code after the C# application was first started, it doesn't get into the WndProc. After the main form is shown (by a double click on the system tray icon, which in essence does a Show()), catching the broadcast message works and keeps working after hiding the form with Hide().

Can anyone explain me why it doesn't work after the first Hide() from the MainForm_Load event handler? Am I hiding the form too early?

EDIT1: It seems like it has nothing to do with the Hide on load. Even without the initial Hide, my main form WndProc will only start accepting broadcast posts after it is hidden and re-shown...


Solution

  • After creating a small test application, I have found out that PostMessage() to HWND_BROADCAST doesn't arrive in Form.WndProc if Form.ShowInTaskbar is set to false while SendMessage() to HWND_BROADCAST does.

    Even though the MSDN note about sending or posting messages to HWND_BROADCAST is exactly the same.

    So it had nothing to do with the hiding or showing of the form and this seems like another undocumented feature of the Windows API.