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

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

同理,在DLL工程中创建定时器也需用这种方法,因为DLL没有窗口,没窗口就没有消息循环,没消息循环就收到不到定时消息。如果DLL有窗口的话,就可以在SetTimer()时指定窗口句柄也行,直接用GetForegroundWindow()得到句柄。

方法:在一个单独的线程中创建定时器,再通过指定的回调函数来处理定时事件。

 

  1. #include <stdio.h>  
  2. #include <windows.h>  
  3. #include <conio.h>  
  4.   
  5. UINT cnt = 0;  
  6.   
  7. //定时器回调函数  
  8. void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);  
  9.   
  10. //线程回调函数  
  11. DWORD CALLBACK ThreadProc(PVOID pvoid);    
  12.   
  13.   
  14. //主函数  
  15. int main()  
  16. {  
  17.     //创建线程  
  18.     DWORD dwThreadId;    
  19.     HANDLE hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThreadId);   
  20.     printf("hello, thread start!\n");  
  21.       
  22.     //得到键盘输入后再退出  
  23.     getch();         
  24.     return 0;  
  25. }      
  26.   
  27. //线程  
  28. DWORD CALLBACK ThreadProc(PVOID pvoid)  
  29. {  
  30.     //强制系统为线程简历消息队列  
  31.     MSG msg;  
  32.     PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);   
  33.       
  34.     //设置定时器  
  35.     SetTimer(NULL, 10, 1000, TimeProc);  
  36.       
  37.     //获取并分发消息  
  38.     while(GetMessage(&msg, NULL, 0, 0))  
  39.     {  
  40.         if(msg.message == WM_TIMER)  
  41.         {  
  42.             TranslateMessage(&msg);    // 翻译消息  
  43.             DispatchMessage(&msg);     // 分发消息  
  44.         }  
  45.     }  
  46.       
  47.     KillTimer(NULL, 10);  
  48.     printf("thread end here\n");  
  49.     return 0;  
  50. }  
  51.   
  52. //定时事件  
  53. void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)  
  54. {  
  55.     cnt ++;  
  56.     printf("thread count = %d\n", cnt);  
  57. }  
#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);
}


jpg改rar

posted @ 2017-03-27 14:46  狂客  阅读(4345)  评论(0编辑  收藏  举报