Visual C++ 游戏编程基础之定时器的使用

一、重要函数

1.定时器函数介绍

  注意事项:1.定时器代号不为0,且在同一个窗口内唯一;

                    2.时间间隔单位是千分之一秒;

                    3.专门处理VM_TIMER消息的函数,若不需要则设为NULL,把消息处理放到WndProc函数中;

2.定时器删除函数

   Bool KillTimer( int  定时器代号 );  

二、基本思路

1.声明位图数组来存储要循环贴图的图片;

2.把每一张图片的名称使用sprintf函数转换成字符串格式存储起来,然后依次加载到位图数组当中;

3.设置定时器,每间隔一段时间,定时器向消息处理函数发送VM_TIMER消息,接着进行绘图,达到循环贴图的目的

三、代码如下


#include "stdafx.h"
#include <stdio.h>

HINSTANCE hInst;
HBITMAP girl[8];//存储各张人物位图
HDC		mdc,hdc;//hdc用于存储窗口DC
int		num;//记录目前显示的图号


ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
void				MyPaint(HDC hdc);


int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	MSG msg;

	MyRegisterClass(hInstance);

	if (!InitInstance (hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	
	return msg.wParam;
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= NULL;
	wcex.hCursor		= NULL;
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= "canvas";
	wcex.hIconSm		= NULL;

	return RegisterClassEx(&wcex);
}


BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;
	char filename[20] = "";
	int i;

	hInst = hInstance;

	hWnd = CreateWindow("canvas", "绘图窗口" , WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	MoveWindow(hWnd,10,10,520,324,true);
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	hdc = GetDC(hWnd);
	mdc = CreateCompatibleDC(hdc);

	for(i=0;i<8;i++)
	{
		sprintf(filename,"girl%d.bmp",i);
		girl[i] = (HBITMAP)LoadImage(NULL,filename,IMAGE_BITMAP,500,281,LR_LOADFROMFILE);
	}
	
	num = 0;
	SetTimer(hWnd,1,100,NULL);//设置定时器,每隔0.1s发送一次消息

	MyPaint(hdc);

	return TRUE;
}


void MyPaint(HDC hdc)
{
	if(num == 8)
		num = 0;

	SelectObject(mdc,girl[num]);
	BitBlt(hdc,0,0,500,281,mdc,0,0,SRCCOPY);

	num++;
}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int i;

	switch (message)
	{
		case WM_TIMER:						
			MyPaint(hdc);
			break;
		case WM_DESTROY:					
			DeleteDC(mdc);
			ReleaseDC(hWnd,hdc);
			for(i=0;i<8;i++)
				DeleteObject(girl[i]);//删除逻辑笔、画笔、字体、位图、区域或者调色板的句柄

			KillTimer(hWnd,1);//删除定时器1

			PostQuitMessage(0);
			break;
		default:						
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

四、效果

猜你喜欢

转载自blog.csdn.net/Sruggle/article/details/90741764
今日推荐