Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
    }
  } 
like image 473
0x26res Avatar asked Feb 25 '23 22:02

0x26res


2 Answers

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.

like image 187
Hans Passant Avatar answered Mar 08 '23 14:03

Hans Passant


Yes, you can. Every thread can have one message loop and you don't need any windows to receive messages or send them (see PostThreadMessage).

There is nothing wrong with using this method if your application is event-driven.

like image 28
0xC0000022L Avatar answered Mar 08 '23 13:03

0xC0000022L