編者按:MFC替我們做了很多工作,學習下詳細流程還是很必要的。
效果圖:
// Win32對話框.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
//定義窗口消息響應函數
LRESULT CALLBACK WndProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
HDC hdc;
RECT rect;
PAINTSTRUCT ps; //接收BeginPaint返回的客戶區繪圖信息
switch(uMsg)//接收GetClientRect返回的客戶區坐標
{
case WM_PAINT:
{
//指針參數一般代表接收函數的返回值,即_out
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
DrawText(hdc, "http://hi.baidu.com/darks00n", -1, &rect, DT_SINGLELINE|DT_CENTER|DT_VCENTER);
EndPaint(hwnd, &ps);
break;
}
case WM_DESTROY: //窗口被關閉後終止對應線程
{
PostQuitMessage(0);
}
default:
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam); //未處理的消息發給默認消息處理函數
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
//第一步.填充WNDCLASS結構體
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW|CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = "WND";
//第二步.注冊窗口類
RegisterClass(&wndclass);
//第三步.創建窗口
HWND hwnd = CreateWindow("WND", "Win32對話框", WS_OVERLAPPEDWINDOW , CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
//第四步.指定顯示窗口狀態
ShowWindow(hwnd, nCmdShow);
//第五步.顯示窗口(發送WM_PAINT消息)
UpdateWindow(hwnd);
//第六步.消息循環(不斷從窗口線程消息隊列中獲取並處理消息)
MSG msg;
//返回值0代表WM_QUIT退出程序,-1代表獲取消息失敗
while (GetMessage(&msg, NULL, 0, 0) > 0 )
{
//翻譯消息(將虛擬鍵消息轉換為字符消息後,再放回窗口消息隊列中)
TranslateMessage(&msg);//注意區分MFC中的PreTranslateMessage函數
//把消息發往消息響應函數(本例中即WndProc)
DispatchMessage(&msg);
}
return msg.wParam;
}