Search code examples
c++windows-messages

Killing old process with BroadcastSystemMessage


I have an application (native C++, Windows), that cannot be run simultaneously on one machine. The behavior that I want to implement is this: on the attempt to run second instance of the application the first one stops running.

To do so I want to use WinApi function BroadcastSystemMessage() something like an example below.

When the application start it sends:

BroadcastSystemMessage(BSF_POSTMESSAGE, &dwRecepients, 0x666, 0, 0);

But, when I run my application in debug mode it doesn't hit

case 0x666:
    int iClose = 0 + 1;
break;

when I start another instance. The other messages are nandled correctly (WM_KEYDOWN, WM_ACTIVATE and others).

What I'm I doing wrong?


Solution

  • In order to broadcast a custom message you need to create an id for it with the RegisterWindowMessage function, for example:

    UINT msg666 = RegisterWindowMessage(L"custom_devil_message");
    

    and use it both in the sending and receiving code:

    // sending code
    BroadcastSystemMessage(BSF_POSTMESSAGE, &dwRecepients, msg666, 0, 0);
    
    // receiving code
    case msg666:
        int iClose = 0 + 1;
    break;
    

    Remember that messages do not work for console applications.