在本文中,我们将讨论Windows应用程序的封装,此处的封装是用函数来封装函数,而不是用类来封装函数(MFC是这样做的)。那么,我们为什么要用函数来封装函数呢?因为这对理解MFC有很大好处。
先看没有封装的程序:
#include <windows.h>
// 回调函数
LRESULT CALLBACK MyFun(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
switch(uMsg)
{
case WM_CLOSE:
if(IDYES == MessageBox(hwnd, "真的要关闭么?", "message", MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
)
{
WNDCLASS wnd;
wnd.cbClsExtra = 0;
wnd.cbWndExtra = 0;
wnd.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wnd.hCursor = LoadCursor(NULL, IDC_CROSS);
wnd.hIcon = LoadIcon(NULL, IDI_ERROR);
wnd.hInstance = hInstance;
wnd.lpfnWndProc = MyFun; // 指定回调函数
wnd.lpszClassName = "ClassName";
wnd.lpszMenuName = NULL;
wnd.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wnd);
HWND hwnd;
hwnd = CreateWindow("ClassName", "温馨提示:", WS_OVERLAPPEDWINDOW,
500, 500, 200, 200, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, SW_SHOWNORMAL);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0)) // 从消息队列中循环地抓取消息
{
// 可以调用TranslateMessage函数来产生新的消息,并投到消息队列中
DispatchMessage(&msg); // 把消息给Windows
}
return msg.wParam;
}
将程序进行封装,得到:
#include <windows.h>
HINSTANCE g_hInst;
HWND g_hWnd;
LRESULT CALLBACK MyFun(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
switch(uMsg)
{
case WM_CLOSE:
if(IDYES == MessageBox(hwnd, "真的要关闭么?", "message", MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
void InitApplication(HINSTANCE hInstance)
{
WNDCLASS wnd;
wnd.cbClsExtra = 0;
wnd.cbWndExtra = 0;
wnd.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wnd.hCursor = LoadCursor(NULL, IDC_CROSS);
wnd.hIcon = LoadIcon(NULL, IDI_ERROR);
wnd.hInstance = hInstance;
wnd.lpfnWndProc = MyFun;
wnd.lpszClassName = "ClassName";
wnd.lpszMenuName = NULL;
wnd.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wnd);
}
void InitInstance(HINSTANCE hInstance, int nCmdShow)
{
g_hWnd = CreateWindow("ClassName", "温馨提示:", WS_OVERLAPPEDWINDOW,
500, 500, 200, 200, NULL, NULL, hInstance, NULL);
ShowWindow(g_hWnd, nCmdShow);
}
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
InitApplication(hInstance);
InitInstance(hInstance, nCmdShow);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
DispatchMessage(&msg);
}
return msg.wParam;
}
InitApplication函数和InitInstance函数是MFC中非常重要的两个函数,理解了上面的程序,可以为理解MFC提供很大帮助。
上面两个程序的作用相同,结果为: