Windows MessageBoxes in C

Creating a MessageBox in C is surprisingly easy. We need to include Windows.h and then call the MessageBox() function as we would in a .Net program.

#include <Windows.h>

int main(){
MessageBox(NULL, NULL, NULL, NULL);
}

Four NULL arguments! 

The first argument to MessageBox() is an HWND, which is an integer handle to the parent window. Let’s leave this NULL, for now. The second argument is the message. Note that this argument / parameter is of type LPCTSTR, which is a pointer to a character string. When passing a string literal as an argument, we will use the TEXT() macro. Basically, LPCTSTR uses Unicode  characters, so we may or may not need to cast the string literal to Unicode. The TEXT() macro takes care of this for us. 

#include <Windows.h>

int main(){

LPCTSTR msg = TEXT("Saluton, Mundo!");

MessageBox(NULL, msg, NULL, NULL);

}

The third argument is the message box title. LIke the message itself, it is an LPCTSTR

#include <Windows.h>

int main(){

LPCTSTR title = TEXT("Message!");

MessageBox(NULL, TEXT("Han shot first!"), title, NULL);

}

The fourth argument to the MessageBox() function can be taken from a set a of dentfined token strings, as in #define ARRAY_BOUNDS 256, that are defined in WINUSER.H. This fourth argument specifies what buttons will be displayed on the MessageBox. We can use the | operator to combine options to define the default option or the icon.

#include <Windows.h>
#include <WinUser.h>
#include <stdio.h>

int main(){

printf("MB_OKCANCEL = %x\n", MB_OKCANCEL);
printf("MB_YESNOCANCEL = %x\n", MB_YESNOCANCEL);
printf("MB_YESNO = %x\n", MB_YESNO);

printf("MB_DEFBUTTON1 = %x\n", MB_DEFBUTTON1);
printf("MB_DEFBUTTON2 = %x\n", MB_DEFBUTTON2);
printf("MB_ICONWARNING = %x\n", MB_ICONWARNING);


}

Note that all of the token strings begin with MB.

#include <Windows.h>
#include <WinUser.h>

int main(){

LPCTSTR message = TEXT("You are likely to be eaten by a Grue.");
LPCTSTR title = TEXT("Zork");

MessageBox(NULL, message, title, MB_RETRYCANCEL | MB_ICONWARNING);

return 0;

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s