您的位置:首页 > 编程语言 > C语言/C++

在c++中如何实现非consle类型的计时器

2007-07-26 17:19 405 查看
/*
UINT_PTR SetTimer(
HWND hWnd, // handle to window
UINT_PTR nIDEvent, // timer identifier
UINT uElapse, // time-out value
TIMERPROC lpTimerFunc // timer procedure
);
一般来说SetTimer方法在mfc的windows应用程序下使用得很多,也很简单,由于基本上
所有的windows窗体都继承了CWnd类,所以只需要将其指定为hWnd,并实现对应的回调
函数(缺省为OnTimer),而对于非mfc的程序,采用可这样的方式实现定时器,但是
个人觉得这种实现方式是否合理并且高效,还值得推敲。

对api的说明就不写了,请大家参阅msdn
*/
///////////////////////////////////////////////////////////////////////////////
// //
// 模块: timertest_main.cpp //
// 开发日期: 2007年07月25日 //
// 最后修改日期: 2007年07月25日 //
// 说明: 这个例子在consle模式下创建了一个定时器,该定时器需要程序自己调用 //
// GetMessage方法来对消息进行分发。具体请参阅msdn的Creating a Timer。 //
// Copyright (c) 2007 皮开元 //
// //
///////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <iostream>

VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime)
{
std::cout << "the time is: " << GetTickCount() << std::endl;
std::cout << "hello, this is TimerPorc." << std::endl;
}

class CMyTimer
{
public:
CMyTimer(int milSecs)
{
//m_timer = Timer;
m_msecs = milSecs;
};

~CMyTimer()
{
killTimer();
};

static void CALLBACK TimerProc_CMyTimer(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime)
{
std::cout << "the time is: " << GetTickCount() << std::endl;
std::cout << "hello, this is TimerProc_CMyTimer." << std::endl;
}

void startTimer(TIMERPROC lpTimerFunc=NULL)
{
if (NULL == lpTimerFunc)
m_timer = SetTimer(NULL, NULL, m_msecs, this->TimerProc_CMyTimer);
else
SetTimer(NULL, m_timer, m_msecs, lpTimerFunc);

std::cout << "timer[" << (int)m_timer << "] start at time : " << GetTickCount() << std::endl;
waitMessage(20);
};
private:
void waitMessage(int iCount)
{
int loop;
MSG msg; // message structure
if (0 >= iCount)
loop = 1000;
else
loop = iCount;

// If your application creates a timer without specifying a window handle, your application must monitor the
// message queue for WM_TIMER messages and dispatch them to the appropriate window.
// Note that GetMessage can return -1 if there is an error
int itemp;
while ( (itemp = GetMessage(&msg, NULL,NULL,NULL))&& (itemp!=0) && (-1 != itemp))
{
if (0 >= loop) break;

TranslateMessage(&msg); // translates virtual-key codes
DispatchMessage(&msg); // dispatches message to window

loop --;
}
};

void killTimer()
{
::KillTimer(NULL, m_timer);
std::cout << "KillTimer is invoked." << std::endl;
};

private:
UINT_PTR m_timer;
int m_msecs;
};

void main()
{
CMyTimer* timer = new CMyTimer(90);
timer->startTimer(TimerProc);
delete timer; timer = NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: