创建一个Win32应用程序的步骤。
1.编写WinMain函数,可以在MSDN上查找并复制。
2.设计窗口类(WNDCLASS)
3.注册窗口类。
4.创建窗口.
5.显示并更新窗口。
6.编写消息循环.
7.编写窗口过程函数。
窗口过程函数的语法,可通过MSDN查看WNDCLASS的IpfnWndProc成员变量,在这个成员的解释中可查到。
#include <Windows.h>
#include <stdio.h>
LRESULT CALLBACK WinSunProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam );
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd )
{
//设计窗口类
WNDCLASS windclass;
windclass.cbClsExtra = 0;
windclass.cbWndExtra = 0;
windclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
windclass.hCursor = LoadCursor(NULL,IDC_CROSS);
windclass.hIcon = LoadCursor(NULL,IDI_ERROR);
windclass.hInstance = hInstance;
windclass.lpfnWndProc = WinSunProc;
windclass.lpszClassName = "tips";
windclass.lpszMenuName = NULL;
windclass.style =CS_HREDRAW | CS_VREDRAW;
RegisterClass(&windclass);
//创建窗口,定义一个变量来保存成功创建窗口返回的句柄
HWND hwnd;
hwnd = CreateWindow("tips","阿良小测",WS_OVERLAPPEDWINDOW,0,0,600,400,NULL,NULL,hInstance,NULL);
//显示及刷新窗口
ShowWindow(hwnd,SW_SHOWNORMAL);
UpdateWindow(hwnd);
//定义消息结构体,开始消息循环
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
//编写窗口过程函数
LRESULT CALLBACK WinSunProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam )
{
switch (uMsg)
{
case WM_CHAR:
char szchar[20];
sprintf_s(szchar,"char is %d",wParam);
MessageBox(hwnd,szchar,"windows",0);
break;
case WM_LBUTTONDOWN:
MessageBox(hwnd,"mouse clicked","windows",0);
HDC hdc;
hdc=GetDC(hwnd); //不能响应WM_PAINT消息时调用
TextOut(hdc,0,50,"第一个窗口",strlen("第一个窗口"));
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDc;
PAINTSTRUCT ps;
hDc = BeginPaint(hwnd,&ps); //BeginPaint智能在响应WM_PAINT消息时调用
TextOut(hDc,0,0,"培训",strlen("培训"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE:
if (IDYES == MessageBox(hwnd,"是否结束?","亲,请留步",MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}