在Win32控制台程序中使用定时器

定时器Timer,是编程中最常用的功能之一,在VC MFC中,定时器功能很好实现,例程也很多,那么在黑漆漆的Win32 Console窗口中如何实现呢?

方法有二,一是使用多媒体时钟来计时,二是用传统Timer只不过需要自己传消息。下面分别贴代码。

1.多媒体时钟

#include"stdlib.h"
#pragma comment(lib,"Winmm.lib")

void CALLBACK TimerProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
{
	printf("Timer\n");

}
void main()
{
	MMRESULT nIDTimerEvent = timeSetEvent(1000, 0, TimerProc, 0, (UINT)TIME_PERIODIC);
	while (1);
}



2.SetTimer

/*Timer process function*/
void CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
        printf("timer\n");
}

/*main function*/
void main()
{
	SetTimer(NULL, 1, 1000, TimerProc);
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (msg.message == WM_TIMER)
		{
			DispatchMessage(&msg);
		}
	}
}


3.线程中使用,在网上看到过类似的东西,不嫌麻烦或者另有他用可以试试:

VOID CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
	printf("timer\n");
}

DWORD CALLBACK Thread(PVOID   pvoid)
{
	MSG  msg;
	PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	UINT  timerid = SetTimer(NULL, 1, 1000, TimerProc);
	BOOL  bRet;


	while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
	{
		if (bRet == -1)
		{
			//   handle   the   error   and   possibly   exit   
		}
		else
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	KillTimer(NULL, timerid);
	printf("thread end here\n");
	return   0;
}

void main()
{
	DWORD   dwThreadId; 	
	HANDLE  hThread = CreateThread(NULL, 0, Thread, 0, 0, &dwThreadId);
	while (1);
}



4.直接用多线程取代定时器

DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
	while(1)
	{
		printf("thread 1\n");
		Sleep(1000);
	}
	return 0;
}

void main()
{
	HANDLE hThread;
	hThread = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	while(1);
}








  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值