Question

Using CoreFoundation, I can display an alert dialog with the following:

CFUserNotificationDisplayAlert(0.0, 
                               kCFUserNotificationPlainAlertLevel, 
                               NULL, NULL, NULL, 
                               CFSTR("Alert title"), 
                               CFSTR("Yes?), 
                               CFSTR("Affirmative"), 
                               CFSTR("Nah"), 
                               NULL, NULL);

How do I replicate this using the Windows C API? The closest I've gotten is:

MessageBox(NULL, "Yes?", "Alert title", MB_OKCANCEL);

but that hard-codes "OK" and "Cancel" as the button titles, which is not what I want. Is there any way around this, or an alternative function to use?

Was it helpful?

Solution

You can use SetWindowText to change the legend on the buttons. Because the MessageBox() blocks the flow of execution you need some mechanism to get round this - the code below uses a timer.

I think the FindWindow code may be dependent on there being no parent for MessageBox() but I'm not sure.

int CustomMessageBox(HWND hwnd, const char * szText, const char * szCaption, int nButtons)
{
    SetTimer( NULL, 123, 0, TimerProc );
    return MessageBox( hwnd, szText, szCaption, nButtons );
}

VOID CALLBACK TimerProc(      
    HWND hwnd,
    UINT uMsg,
    UINT_PTR idEvent,
    DWORD dwTime
)
{
    KillTimer( hwnd, idEvent );
    HWND hwndAlert;
    hwndAlert = FindWindow( NULL, "Alert title" ); 
    HWND hwndButton;
    hwndButton = GetWindow( hwndAlert, GW_CHILD );
    do
    {
        char szBuffer[512];
        GetWindowText( hwndButton, szBuffer, sizeof szBuffer );
        if ( strcmp( szBuffer, "OK" ) == 0 )
        {
            SetWindowText( hwndButton, "Affirmative" );
        }
        else if ( strcmp( szBuffer, "Cancel" ) == 0 )
        {
            SetWindowText( hwndButton, "Hah" );
        }
    } while ( (hwndButton = GetWindow( hwndButton, GW_HWNDNEXT )) != NULL );
}

OTHER TIPS

The Windows MessageBox function only supports a limited number of styles. If you want anything more complicated that what's provided, you'll need to create your own dialog box. See MessageBox for a list of possible MessageBox types.

If you decide to make your own dialog box, I'd suggest looking at the DialogBox Windows function.

If you're willing to tie yourself to Windows Vista and above, you might want to consider the "TaskDialog" function. I believe it will allow you do do what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top