版本一:對於使用“掩碼”傳遞參數的方法,簡單的實現思路:
#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;
}