开发者

Display alert with custom button titles on Windows?

开发者 https://www.devze.com 2022-12-13 22:19 出处:网络
Using CoreFoundation, I can display an alert dialog with the following: CFUserNotificationDisplayAlert(0.0,

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?


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 );
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消