在win32控制台应用程序中实现定时器

1.SetTimer:在控制台应用程序中同样可以用SetTimer实现定时器的效果。

普通的win32程序中定时器的应用很多也很方便,但是在win32控制台中也是可以使用定时器的,利用的是windows程序的消息循环机制,如下:

#include<iostream>
#include<windows.h>
using namespace std;

//定时器ID
DWORD dwTimerId = 0;


void CALLBACK TimeProc( HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{    	
	if (dwTimerId == idEvent)
	{
		cout<<"触发定时器!"<<endl; 
	}
}
    
    
int main()
{
	//必须用消息循环,否则Timer无效
	//返回值位定时器ID,而不是参数1
	dwTimerId = SetTimer(NULL,1,1000,TimeProc);
	MSG msg;
	while(GetMessage(&msg,NULL,0,0))
	{
		if(msg.message==WM_TIMER)
		{
			DispatchMessage(&msg);
		}                       
	}
    
	return 0;
} 

2. 线程+SetTimer:网上牛人用线程做的相同效果

#include   <windows.h>
#include   <stdio.h>
#include   <conio.h>

int count   =0;
DWROD dwTimerId = 0;

VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	if (dwTimerId == idEvent)
	{
		count++;
		printf("WM_TIMER in work thread count=%d\n",count);
	}
}

DWORD CALLBACK Thread(PVOID pvoid)
{
    MSG  msg;
    PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);
    dwTimerId = SetTimer(NULL,111,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;
}

int main()
{
    DWORD dwThreadId = 0;
    printf("use timer in workthread of console application\n");
    HANDLE hThread = CreateThread(NULL,0,Thread,0,0,&dwThreadId);

    getch();
    return 0;
}

3. timeSetEvent  --  Windows多媒体高精度定时器

函数:MMRESULT timeSetEvent(UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, WORD dwUser, UINT fuEvent)
说明:
uDelay:以毫秒指定事件的周期。
        Uresolution:以毫秒指定延时的精度,数值越小定时器事件分辨率越高。缺省值为1ms。
        LpTimeProc:指向一个回调函数。
        DwUser:存放用户提供的回调数据。
        FuEvent:指定定时器事件类型:
        TIME_ONESHOT:uDelay毫秒后只产生一次事件
        TIME_PERIODIC :每隔uDelay毫秒周期性地产生事件。

#include<iostream>
#include<windows.h>
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
using namespace std;


void CALLBACK TimeProc(UINT uID,UINT uMsg,DWORD dwUser,DWORD dw1,DWORD dw2)
{
	cout<<"定时器触发!"<<endl;
}

int main()
{
	timeSetEvent( 1000,0, TimeProc, 0, (UINT)TIME_PERIODIC);
	getchar();
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值