c++messageboxvcl

How to detect which Yes/No/Cancel button was clicked in a Messagebox


I am using a VCL Forms application in C++ Builder.

How do I display a Messagebox with Yes/No/Cancel buttons and then detect if the yes, the no or the cancel button is pressed.

Here is my code:

if(MessageBox(NULL, "Test message", "test title",  MB_YESNOCANCEL) == IDYES) {}

I have included the following:

#include <windows.h>

I am getting the following errors:

E2034 Cannot convert 'char const[13]' to 'const wchar_t *'

E2342 Type mismatch in parameter 'lpText' (wanted 'const wchar_t *', got 'const char *')

Solution

  • You need to use wide characters in the call to MessageBox and you need to store the result in a variable, before working out what to do next.

    const int result = MessageBox(NULL, L"Test message", L"test title",  MB_YESNOCANCEL);
    
    switch (result)
    {
    case IDYES:
        // Do something
        break;
    case IDNO:
        // Do something
        break;
    case IDCANCEL:
        // Do something
        break;
    }
    

    You should read the documentation for MessageBox.