Search code examples
cwinapiconditional-statementsmessagebox

Conditioning Yes or No in C MessageBox()


I had a problem of conditioning what I want this MessageBox() to do when a user clicks "Yes" or "No".

Here is my pseudo code show what I mean:

MessageBox(0,"Click \"Yes\" or \"No\".","A MessageBox() Example",4);
    if(TheUserClickedYes){
        //Do something
    }else if(TheUserClickedNo){
       // Do Something else
    }

The 4 in the last parameter displays "Yes" or "No" buttons. I can get the box to display, but when I try to condition the buttons, I don't know how to do it. I tried to Google it and all that displayed in the results was C++ or C#. I am trying to do it in C. Thank you in advance.


Solution

  • MessageBox will return an integer indicating which button was clicked, in case of success.

    Rewrite your code to use the appropriate constants instead of hardcoding numbers:

    switch (MessageBox(NULL, TEXT("Click \"Yes\" or \"No\".", TEXT("A MessageBox() Example"), MB_YESNO)) {
    case IDYES:
        MessageBox(NULL, TEXT("Yes!"), TEXT("Yes"), MB_OK);
        break;
    case IDNO:
        MessageBox(NULL, TEXT("No!"), TEXT("No"), MB_OK);
        break;
    default:
        /* An error occurred. */
    }
    

    Always read carefully the documentation of the API you're using before using it.