下面是一个最简单的win32的窗体。
#include "stdafx.h"
LRESULT CALLBACK MainWndProc(HWND,UINT,WPARAM,LPARAM);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
char szClassName[]="MainWClass";
WNDCLASSEX wndClass;
wndClass.cbSize=sizeof(wndClass);
wndClass.style=CS_HREDRAW|CS_VREDRAW;
wndClass.lpfnWndProc=MainWndProc;
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(WHITE_BRUSH);
wndClass.lpszMenuName=NULL;
wndClass.lpszClassName=szClassName;
wndClass.hIconSm=NULL;
//注册这个窗口类
::RegisterClassEx(&wndClass);
//创建主窗口
HWND hwnd=::CreateWindowEx(
0,
szClassName,
"My frist Wndiows",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
if(hwnd==NULL)
{
::MessageBox(NULL,"创建窗口失败!","error",MB_OK);
return -1;
}
//显示窗口,刷新窗口客户区
::ShowWindow(hwnd,nCmdShow);
::UpdateWindow(hwnd);
//从消息队列中取出消息,交给窗口函数处理,直到GetMessage返回False,结束消息循环
MSG msg;
while(::GetMessage(&msg,NULL,0,0))
{
//转化键盘消息
::TranslateMessage(&msg);
//将消息发送到相应的窗口函数
::DispatchMessage(&msg);
}
//当GetMessage返回False时程序结束
return msg.wParam;
}
LRESULT CALLBACK MainWndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
char szText[]="最简单的窗口程序!";
switch(uMsg)
{
case WM_PAINT:
HDC hdc;
PAINTSTRUCT ps;
//使无效的客户区变的有效,并取得设备环境句柄
hdc=::BeginPaint(hwnd,&ps);
//显示文字
::TextOut(hdc,10,10,szText,strlen(szText));
::EndPaint(hwnd,&ps);
return 0;
case WM_DESTROY:
//向消息队列投递一个WM_QUIT消息,促使GetMessage函数返回0,结束消息循环
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hwnd,uMsg,wParam,lParam);
}
从上面的代码中,我们不然看出在桌面上显示一个窗体的步骤:
1.注册窗口类
2.创建窗口
3.在桌面上显示窗口
4.更新窗口客户区
5.进入windows消息循环