1. Windows 应用程序运行机制
#include#include 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应用程序的内部运行机制。