Search code examples
c++windowsvisual-c++message-queuewindows-messages

Can I use my own message loop in windows?


I am building a C++ program, on windows, using Visual Studio. It relies on a COM base API, that sends windows message for notification.

To process those messages, I see two possibilities:

  • Create a windows form and call doModal on it which should process the messages, but since I don't want to use any UI, it's not what I want to do
  • make my own loop for processing messages

I don't know what is best, or if there is another way to process the messages (there is probably a windows function that can launch the loop)

  while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
  { 
    if (bRet == -1)
    {
      // handle the error and possibly exit
    }
    else
    {
      TranslateMessage(&msg); 
      DispatchMessage(&msg); 
    }
  } 

Solution

  • It is not just for your own benefit, COM requires you to create a message loop. COM needs it to handle apartment threaded COM servers, an expensive word for "components that don't support multi-threading". The vast majority of them don't.

    It is best to create a window, it doesn't have to be visible. That gives you a HWND that you can use in your SendMessage() calls. The window procedure you write can process the messages. From there, it gets to be easy to create a minimal user interface, with Shell_NotifyIcon for example. Always nice when you can display a notification when something goes wrong. So much better then an event in a log that nobody ever looks at.