Win32控制台中使用定时器的方法

在MFC中用OnTimer()函数就可以很方便的实现定时事件,但在Win32控制台工程中没有消息循环,,MSDN里也不推荐把SetTimer()用在Console Applications里。

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控制台中使用定时器的方法

相关文章:

你感兴趣的文章:

标签云: