在这一节我先给出一个模板程序来,win32编程基本就是参照这个模板的,只不过在这基础上多调用几个api函数罢了。这个程序最好自己敲一下,以后都是这个样子编程。
#include<windows.h>
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib ")
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);//窗口过程函数的声明
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,
PSTR szCmdLine,int iCmdShow)
{
static TCHAR szAppName[]=TEXT("nameofwindow");
HWND hwnd;//窗口句柄对象
MSG msg;//消息对象
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(WHITE_BRUSH);
wndclass.lpszClassName=szAppName;
wndclass.lpszMenuName=NULL;
if(!RegisterClass(&wndclass))//判断窗口是否注册成功,很重要
{
MessageBox(NULL,TEXT("error"),szAppName,MB_ICONERROR);
return 0;
}
hwnd=CreateWindow(szAppName,//创建窗口
TEXT("THIS IS THE WINDOW"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd,iCmdShow);//显示和更新窗口
UpdateWindow(hwnd);
while(GetMessage(&msg,NULL,0,0))//消息循环
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)//窗口过程函数
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch(message)//消息的处理
{
case WM_CREATE:
PlaySound(TEXT("a.wav"),NULL,SND_FILENAME|SND_ASYNC);
case WM_PAINT:
hdc=BeginPaint(hwnd,&ps);
GetClientRect(hwnd,&rect);
DrawText(hdc,TEXT("hello"),-1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
EndPaint(hwnd,&ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd,message,wParam,lParam);
}