Win32 Application,沒有基於MFC的類庫,而是直接調用C++接口來編程。
一、彈出消息窗口
(1)最簡單的,在當前窗口中彈出新窗口。新窗口只有“YES”按鈕。
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "我的Win32程序", "HelloWorld", MB_OK); return 0; }
(2)獲取已經打開的窗口,並在該窗口中彈出新窗口,而且新窗口有“YES/NO/CANCEL”按鈕,可以捕獲該返回值。
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. HWND hWnd = ::FindWindow(NULL, "無標題 - 記事本"); int nRet = MessageBox(hWnd, "我的Win32程序", "HelloWorld", MB_YESNOCANCEL|MB_ICONQUESTION); if(IDYES == nRet){ MessageBox(hWnd, "你點擊了\"是\"按鈕", "返回值", 0); } else if(IDNO == nRet){ MessageBox(hWnd, "你點擊了\"否\"按鈕", "返回值", 0); } else{ MessageBox(hWnd, "你點擊了\"取消\"按鈕", "返回值", 0); } return 0; }
二、對話框
(1)通過DialogBox新增一個對話框,並設置對話框的消息處理回調函數MainProc,接收對話框的返回值並做相應處理:
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int nRet; nRet = DialogBox(hInstance, (LPCSTR)IDD_DIALOG1, NULL, MainProc); if(IDCANCEL == nRet){ MessageBox(NULL, "CANCEL", "返回值", 0); return -1; } return 0; }
回調函數中,通過GetDlgItemInt獲取對話框的輸入整型值、通過SetDlgItemInt設置對話框的輸出整型值(如果是字符串,Int改為Text),通過EndDialog關閉對話框,並返回不同的返回值:
BOOL CALLBACK MainProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { OutputDebugString("測試運行狀態\n"); if(WM_COMMAND == uMsg) { if(LOWORD(wParam) == IDCANCEL){ EndDialog(hwndDlg, IDCANCEL); return IDCANCEL; } else if(LOWORD(wParam) == IDOK){ int nLeft = GetDlgItemInt(hwndDlg, IDC_LEFT, NULL, TRUE); int nRight = GetDlgItemInt(hwndDlg, IDC_RIGHT, NULL, TRUE); int nResult = nLeft + nRight; SetDlgItemInt(hwndDlg, IDC_RESULT, nResult, TRUE); } } return FALSE; }
備注:
對話框的資源屬性,可以編輯彈出位置、對其方式、顯示效果、是否可編輯等等。
Ctrl+D,可以編輯對話框的焦點順序。