1. Windows 應用程式運行機制
#include <Windows.h>#include <stdio.h>LRESULT CALLBACK WinExample1Proc( //對視窗過程函數進行聲明 HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);int WINAPI WinMain( //Win32應用程式入口函數 HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ WNDCLASS wndcls; //建立一個視窗類別 wndcls.cbClsExtra = 0; wndcls.cbWndExtra = 0; wndcls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndcls.hCursor = LoadCursor(NULL, IDC_CROSS); wndcls.hIcon = LoadIcon(NULL, IDI_ERROR); wndcls.hInstance = hInstance; wndcls.lpfnWndProc = WinExample1Proc; wndcls.lpszClassName =(LPCWSTR)"Example1"; wndcls.lpszMenuName = NULL; wndcls.style = CS_HREDRAW | CS_VREDRAW; RegisterClass(&wndcls); //註冊視窗類別 HWND hwnd; //建立視窗,定義一個控制代碼來唯一標識該視窗 hwnd = CreateWindow((LPCWSTR)"example1",(LPCWSTR)"一個windows應用程式視窗", WS_OVERLAPPEDWINDOW, 0,0,500,500,NULL,NULL,hInstance,NULL); ShowWindow(hwnd, SW_SHOWNORMAL); //顯示和更新視窗 UpdateWindow(hwnd); MSG msg; while(GetMessage(&msg, NULL, 0, 0)) //定義訊息結構體,並進行訊息迴圈 { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam;}LRESULT CALLBACK WinExample1Proc( //編寫視窗過程函數,實現訊息處理 HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ char exChar2[] = {"第一個Windows應用程式"}; switch (uMsg) { case WM_CHAR: char exChar1[40]; sprintf(exChar1, "鍵盤輸入字元的ASCII值為: %d", wParam); MessageBox(hwnd, (LPCWSTR)exChar1, (LPCWSTR)"char", 0); break; case WM_RBUTTONDOWN: MessageBox(hwnd, (LPCWSTR)"右鍵被按下", (LPCWSTR)"message", 0); break; case WM_CLOSE: if (IDYES == MessageBox(hwnd, (LPCWSTR)"要結束嗎?", (LPCWSTR)"提示:", MB_YESNO)) { DestroyWindow(hwnd); } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: HDC hDC; PAINTSTRUCT ps; hDC = BeginPaint(hwnd, &ps); RECT rt; GetClientRect(hwnd, &rt); DrawText(hDC, (LPCWSTR)exChar2, strlen(exChar2), &rt, DT_CENTER); EndPaint(hwnd, &ps); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0;}
從上面的程式結構中,可以發現Win32應用程式有一條很明確的主線: 首先進入WinMain函數,然後設計視窗類別,註冊視窗類別,產生視窗,註冊視窗,顯示視窗,更新視窗,最後進入訊息迴圈,將訊息路由到視窗過程函數中去處理。 這是典型的Windows應用程式的內部運行機制。