martes, 4 de mayo de 2010

MessageBox: From Windows to Mac

It's difficult to find good help resources when you are coding in x-studio and you came from win32 coding.
One trivial thing that is showing a message box goes difficult if you don't use the right API.

Searching the Internet, you will probably end with CreateStandardAlert, RunStandardAlert, StandardAlert, or some similar function, a dialog dispayed but without correct behavior...

I have good results using CFUserNotification API's CFUserNotificationDisplayAlert

for a starting point the code will be:

#define IDOK       1
#define IDCANCEL   2
int MessageBox( char* header, char* message, unsigned long message_type )
    //convert the strings from char* to CFStringRef
    CFStringRef header_ref      = CFStringCreateWithCString( NULL, header,     strlen(header)    );
    CFStringRef message_ref  = CFStringCreateWithCString( NULL, message,  strlen(message) );
    CFOptionFlags result;  //result code from the message box
    //launch the message box
                                   0, // no timeout
                                   kCFUserNotificationNoteAlertLevel, //change it depending message_type flags ( MB_ICONASTERISK.... etc.)
                                   NULL, //icon url, use default, you can change it depending message_type flags
                                   NULL, //not used
                                   NULL, //localization of strings
                                   header_ref, //header text 
                                   message_ref, //message text
                                   NULL, //default "ok" text in button
                                   CFSTR("Cancel"), //alternate button title
                                   NULL, //other button title, null--> no other button
                                   &result //response flags
    //Clean up the strings
    CFRelease( header_ref );
    CFRelease( message_ref );
    //Convert the result
    if( result == kCFUserNotificationDefaultResponse )
        return IDOK;
        return IDCANCEL;

Some constants should be defined, and if you want Win-Mac compatible code, they should be defined with windows values.

This sample is equivalent to calling a Win32 MessageBox with MB_OKCANEL flag. Starting from it, should be very easy to implement all the messagebox flags and have a function compatible with windows code

3 comentarios:

Blue dijo...

Your code snippet does not compile and requires further modification.

If you're going to advertise across blogs I would recommend testing the code first or advising users it's untested.

Jorge Arimany Españaque dijo...

Thank you Blue, there was minimal misspelling in the code, I have updated it and now it is ok.

Farid Ahmad dijo...

Very Useful. Worked perfectly first time. Thanks !!