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,可由返回时值获取.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值