Win32窗口创建过程
编写窗口程序的步骤:
1 定义WinMain函数
2 定义窗口处理函数–自己定义处理消息
3 注册窗口类(往OS写入数据)
4 创建窗口 (在内存中创建窗口)
5 显示窗口(根据内存中对于窗口的描述信息,在显示器中绘制窗口)
6 消息循环(提取/翻译/派发)
7 消息处理
#include "stdafx.h"
HINSTANCE g_hInstance = 0;
//窗口处理函数
LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg,
WPARAM wParam, LPARAM lParam )
{
switch( uMsg )
{
case WM_DESTROY:
PostQuitMessage( 0 );//可以使GetMessage返回0??
break;
}
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
//注册窗口类
BOOL Register( LPSTR lpClassName, WNDPROC wndProc )
{
WNDCLASSEX wce = { 0 };
wce.cbSize = sizeof( wce );
wce.cbClsExtra = 0;
wce.cbWndExtra = 0;
wce.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wce.hCursor = NULL;
wce.hIcon = NULL;
wce.hIconSm = NULL;
wce.hInstance = g_hInstance;
wce.lpfnWndProc = wndProc;
wce.lpszClassName = lpClassName;
wce.lpszMenuName = NULL;
wce.style = CS_HREDRAW | CS_VREDRAW;
ATOM nAtom = RegisterClassEx( &wce );
if( nAtom==0 )
return FALSE;
return TRUE;
}
//创建主窗口
HWND CreateMain( LPSTR lpClassName, LPSTR lpWndName )
{
HWND hWnd = CreateWindowEx( 0, lpClassName, lpWndName,
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
NULL, NULL, g_hInstance, NULL );
return hWnd;
}
//显示窗口
void Display( HWND hWnd )
{
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
}
//消息循环
void Message( )
{
MSG nMsg = { 0 };
while( GetMessage(&nMsg, NULL, 0, 0) )
{
TranslateMessage( &nMsg );
DispatchMessage( &nMsg );
}
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
g_hInstance = hInstance;
BOOL nRet = Register( "Main", WndProc );
if( nRet == FALSE )
{
MessageBox( NULL, "注册失败", "Infor", MB_OK );
return 0;
}
HWND hWnd = CreateMain( "Main", "window" );
Display( hWnd );
Message( );
return 0;
}