Win32控制台中使用定时器的方法
在MFC中用OnTimer()函数就可以很方便的实现定时事件,但在Win32控制台工程中没有消息循环,MSDN里也不推荐把SetTimer()用在Console Applications里。
同理,,在DLL工程中创建定时器也需用这种方法,因为DLL没有窗口,没窗口就没有消息循环,没消息循环就收到不到定时消息。如果DLL有窗口的话,就可以在SetTimer()时指定窗口句柄也行,直接用GetForegroundWindow()得到句柄。
方法:在一个单独的线程中创建定时器,再通过指定的回调函数来处理定时事件。
#include <stdio.h>
#include <windows.h>
#include <conio.h>
UINT cnt = 0;
//定时器回调函数
void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);
//线程回调函数
DWORD CALLBACK ThreadProc(PVOID pvoid);
//主函数
int main()
{
//创建线程
DWORD dwThreadId;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThreadId);
printf("hello, thread start!\n");
//得到键盘输入后再退出
getch();
return 0;
}
//线程
DWORD CALLBACK ThreadProc(PVOID pvoid)
{
//强制系统为线程简历消息队列
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
//设置定时器
SetTimer(NULL, 10, 1000, TimeProc);
//获取并分发消息
while(GetMessage(&msg, NULL, 0, 0))
{
if(msg.message == WM_TIMER)
{
TranslateMessage(&msg); // 翻译消息
DispatchMessage(&msg);
// 分发消息
}
}
KillTimer(NULL, 10);
printf("thread end here\n");
return 0;
}
//定时事件
void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{
cnt ++;
printf("thread count = %d\n", cnt);
}
Win32控制台中使用定时器的方法
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70659.html