11.子視窗控制元件
阿新 • • 發佈:2018-12-15
Windows提供了幾個預定義的類供我們使用,我們一般將他們叫做子視窗控制元件,簡稱控制元件;
控制元件會自己處理訊息,並在自己狀態發生改變時通知父視窗;
預定義的控制元件有:
按鈕、複選框、編輯框、靜態字串標籤和滾動條;
用效果如下的案例來來練習使用子視窗控制元件:
/*------------------------------- MyWindows.c ---------------------------------*/ #include <Windows.h> #include <Strsafe.h> #define IDC_EDIT_1 0x100 #define IDC_BUTTON_1 0x101 #define IDC_BUTTON_2 0x102 HINSTANCE g_hInstance; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, //入口函式,WINAPI即是__stdcall(函式呼叫約定的一種) HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { g_hInstance = hInstance; static TCHAR szAppName[] = TEXT("MyWindows");//定義視窗類的名字 HWND hwnd; //視窗控制代碼定義 MSG msg; //定義訊息 WNDCLASS wndclass; //Windows類定義 wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; //背景,先要得到畫刷控制代碼傳回 wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);//游標 wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);//圖示 wndclass.hInstance = g_hInstance;//模組控制代碼,如前面說的.exe .dll等地址 wndclass.lpfnWndProc = WndProc;//過程函式 wndclass.lpszClassName = szAppName; //類名 wndclass.lpszMenuName = NULL;//選單 wndclass.style = CS_HREDRAW | CS_VREDRAW;//調整寬度和高度重新繪製視窗 if (!RegisterClass(&wndclass)){ //填完視窗類註冊該視窗類 MessageBox(NULL, TEXT("此程式需要在Windows NT平臺上執行!"), szAppName, MB_ICONERROR); return 0; } //建立視窗並設定其具體特徵,返回視窗控制代碼,視窗類名 hwnd = CreateWindow(szAppName, TEXT("Win模板"), //視窗標題 WS_OVERLAPPEDWINDOW, //類風格的擴充套件 CW_USEDEFAULT, //初始視窗座標 CW_USEDEFAULT, 600, 500, NULL, //有無父視窗 NULL, //有無選單 g_hInstance, NULL ); ShowWindow(hwnd, iCmdShow);//顯示視窗 UpdateWindow(hwnd); //更新視窗 while (GetMessage(&msg, NULL, 0, 0)){ TranslateMessage(&msg); //翻譯訊息 DispatchMessage(&msg); //派送訊息到系統,系統再呼叫WinProc函式處理訊息 } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)//傳入訊息結構體的前四個引數 { TCHAR szOutBuffer[0x80] = {0}; //StringCchPrintf(szOutBuffer, 0x80, TEXT("訊息:%x\n"), message); //OutputDebugString(szOutBuffer);//用來看產生什麼訊息 switch (message) { case WM_CREATE: CreateWindow(TEXT("EDIT"), //文字框 NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE, 0, 0, 500, 500, hwnd, IDC_EDIT_1, g_hInstance, NULL ); CreateWindow(TEXT("BUTTON"), //按鈕 TEXT("設定"), WS_CHILD | WS_VISIBLE, 520, 380, 60, 30, hwnd, IDC_BUTTON_1, g_hInstance, NULL ); CreateWindow(TEXT("BUTTON"), //按鈕 TEXT("獲取"), WS_CHILD | WS_VISIBLE, 520, 420, 60, 30, hwnd, IDC_BUTTON_2, g_hInstance, NULL ); return 0; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_BUTTON_1: SetDlgItemText(hwnd, IDC_EDIT_1, TEXT("測試")); return 0; case IDC_BUTTON_2: GetDlgItemText(hwnd, IDC_EDIT_1, szOutBuffer, 0x80); MessageBox(hwnd, szOutBuffer, TEXT("讀到資料"), MB_OK); return 0; } return 0; case WM_DESTROY: //點選右上角關閉傳送WM_DESTROY訊息 PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }