SetTimer在無窗口和有窗口線程的使用 .


今天犯了一個粗心的錯誤,在無窗口線程中,SetTimer中設置計時器ID,而WM_TIMER消息響應函數中得到的計時器ID卻不是之前設置的計時器ID.

// 111902.cpp : Defines the entry point for the console application.  
//  
//#include "stdafx.h"  
#include "stdio.h"  
#include "windows.h"  
BOOL DispatchThreadMessage(MSG* pMsg);  
VOID CALLBACK OnTimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime);  
int main(int argc, char* argv[])  
{  
    printf("Hello World!\n");  
    ::SetTimer(NULL,45,1000,OnTimerProc);  
    MSG msg;  
    while (GetMessage(&msg, 0, 0, 0) > 0)  
    {  
        if (msg.hwnd == NULL && DispatchThreadMessage(&msg))  
            continue;  
        TranslateMessage(&msg);  
        DispatchMessage(&msg);  
    }  
    return 0;  
}  
  
BOOL DispatchThreadMessage(MSG* pMsg)  
{  
    if(pMsg->message == 0x0113)  
    {  
        printf("DispatchThreadMessage: %6d\n",pMsg->wParam);  
        return false;         
    }  
    return false;  
}   
VOID CALLBACK OnTimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)  
{  
    printf("OnTimerProc: %6d\n",idEvent);  
}  

 

對應計時器ID的輸出的是一個隨機數字.

 

原來在msdn中

nIDEvent
[in] Specifies a nonzero timer identifier. If the  hWnd parameter is NULL, and the  nIDEvent does not match an existing timer then it is ignored and a new timer ID is generated. If the  hWnd parameter is not NULL and the window specified by  hWnd already has a timer with the value  nIDEvent , then the existing timer is replaced by the new timer. When  SetTimer replaces a timer, the timer is reset. Therefore, a message will be sent after the current time-out value elapses, but the previously set time-out value is ignored. If the call is not intended to replace an existing timer,  nIDEvent should be 0 if the  hWnd is NULL.
注:只有當hWnd參數為非空時,計時器的ID為設置的  nIDEvent,  否則系統為你自動生成一個計時器ID,可由返回時值獲取.
參考:http://blog.csdn.net/chenyujing1234/article/details/7668642


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM