版本一:对于使用“掩码”传递参数的方法,简单的实现思路:
#include <stdio.h> #define MB_OK 0x00000000 #define MB_OKCANCEL 0x00000001 #define MB_ICONHAND 0x00000010 #define MB_ICONQUESTION 0x00000020 #define MAX_RESULT 0xFFFFFFFF int MessageBox(const char *context, unsigned int type) { if(MAX_RESULT == (~MB_ICONHAND | type)) { printf("\t图标: 信息\t"); } else if(MAX_RESULT == (~MB_ICONQUESTION | type)) { printf("\t图标: 问题\t"); } printf("内容:%s\t", context); if(MAX_RESULT == (~MB_OKCANCEL | type)) { printf("按钮:确定 取消\t"); } else if(MAX_RESULT == ((~MB_OK | type))) { printf("按钮:确定\t"); } putchar('\n'); return 0; } int main(int argc, char *argv[]) { //unsigned int m_o = 0x00000001, m_o1 = 0x00000020, m_o2 = m_o | m_o1; //printf("%x", ~m_o | m_o2); MessageBox("hello, world", MB_OK | MB_ICONHAND); MessageBox("hello, world", MB_OK | MB_ICONQUESTION); MessageBox("hello, world", MB_OKCANCEL | MB_ICONHAND); MessageBox("hello, world", MB_OKCANCEL | MB_ICONQUESTION); printf("---------------------------------------------------\n"); MessageBox("hello, world", MB_OK); MessageBox("hello, world", MB_OKCANCEL); MessageBox("hello, world", MB_ICONHAND); MessageBox("hello, world", MB_ICONQUESTION); return 0; }
版本二:充分利用位运算的特性,大大减少了代码量
#include <stdio.h> #define MB_OK 0x00000000 #define MB_OKCANCEL 0x00000001 #define MB_ABORTRETRYIGNORE 0x00000002 #define MB_ICONHAND 0x00000010 #define MB_ICONQUESTION 0x00000020 #define MB_TYPEMASK 0x0000000F #define MB_ICONMASK 0x000000F0 #define MB_VALIDATE 0x00000000 char *TypeText[3] = {{"OK"},{"OK CANCEL"},{"ABORT RETRY IGNORE"}}; char *Icon[2] = {{"ICONHAND"}, {"ICONQUESTION"}}; int MessageBox(const char *context, unsigned int type) { printf(TypeText[type & MB_TYPEMASK]); putchar('\n'); printf("内容:%s\t", context); putchar('\n'); if((type & MB_ICONMASK) == MB_VALIDATE) { printf("\n-------------------------\n"); return -1; } printf(Icon[((type & MB_ICONMASK)>>4) - 1]); printf("\n-------------------------\n"); return 0; } int main(int argc, char *argv[]) { MessageBox("hello, world", MB_OK | MB_ICONHAND); MessageBox("hello, world", MB_OK | MB_ICONQUESTION); MessageBox("hello, world", MB_OKCANCEL | MB_ICONHAND); MessageBox("hello, world", MB_OKCANCEL | MB_ICONQUESTION); MessageBox("hello, world", MB_OK); MessageBox("hello, world", MB_OKCANCEL); MessageBox("hello, world", MB_ICONHAND); MessageBox("hello, world", MB_ICONQUESTION); return 0; }