首页 / C++ / C++控制台程序中使用定时器
C++控制台程序中使用定时器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++控制台程序中使用定时器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2354字,纯文字阅读大概需要4分钟。
内容图文
转自博客: http://www.cnblogs.com/phinecos/archive/2008/03/08/1096691.html
作者:洞庭散人
“我现在项目是一个控制台程序,用到的Win32API都是与界面无关的,今天需要加入定时器刷新的功能,由于没有消息循环,所以WM_TIMER消息应该如何处理呢?综合了下网上找到的资料,写了个简单的demo,个人以为这种在一个线程中创建定时器,再通过指定的回调函数来处理定时器触发的模式是比较好的。”
demo:
#include <Windows.h>
#include
<stdio.h>
#include <conio.h>
int count = 0;
void CALLBACK TimerProc(HWND hWnd,UINT uMsg,UINT_PTR
idEvent,DWORD dwTime)
{
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);
UINT
timerid = SetTimer(NULL,111,3000,TimerProc);
BOOL bRet;
while
((bRet = GetMessage(&msg,NULL,0,0))!=0)
{
if (bRet
== -1)
{
printf("Error:the thread will
quit,error id is
%d/n",GetLastError());
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(NULL,timerid);
printf("thread
end here/n");
return 0;
}
int main()
{
DWORD dwThreadID;
printf("use
timer in workthread of console application/n");
HANDLE hThread =
CreateThread(NULL,0,Thread,NULL,0,NULL);
_getch();
return
0;
};
本人在了解了作者的意图以后,也做了一个类封装:
#include <Windows.h>
#include
<stdio.h>
#include <conio.h>
class CTimer
{
public:
CTimer();
void
CreateTimerThread(int* pi);
static DWORD CALLBACK TimeThread(PVOID
pvoid);
static void CALLBACK TimeProc(HWND hWnd,UINT uMsg,UINT_PTR
idEvent,DWORD dwTime);
};
CTimer::CTimer()
{
}
void CTimer::CreateTimerThread(int* pi)
{
HANDLE hand
= CreateThread(NULL,0,CTimer::TimeThread,pi,0,NULL);
}
DWORD CALLBACK CTimer::TimeThread(PVOID pvoid)
{
int*
pi = (int*)pvoid;
int itm = *pi;
MSG
msg;
PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);
UINT
timeid = SetTimer(NULL,111,itm,CTimer::TimeProc);
BOOL
bRet;
while ((bRet =
GetMessage(&msg,NULL,0,0))!=0)
{
if (bRet ==
-1)
{
printf("Error:the thread will
quit,error id is
%d/n",GetLastError());
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(NULL,timeid);
printf("thread
end here/n");
return 0;
}
void CALLBACK CTimer::TimeProc(HWND hWnd, UINT uMsg, UINT_PTR
idEvent, DWORD dwTime)
{
printf("WM_TIMER in work thread
count/n");
}
int main()
{
int iTime = 1000;
int* pi =
&iTime;
CTimer* ptime = new
CTimer;
ptime->CreateTimerThread(pi);
_getch();
return
0;
};
感谢洞庭散人...
原文:http://www.cnblogs.com/huxu/p/3580397.html
内容总结
以上是互联网集市为您收集整理的C++控制台程序中使用定时器全部内容,希望文章能够帮你解决C++控制台程序中使用定时器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。