SetTimer设置后没法调用定时器函数(回调函数)吗?

972 篇文章 329 订阅
32 篇文章 6 订阅

       我们先来看一个简单的程序:

 

#include <iostream>
#include <windows.h>
using namespace std;

void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
	cout << "hello" << endl;
}

int main()
{
	SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc);

	while(1);

	return 0;
}

      我们预期程序会每秒打印一次hello, 但有点奇怪, 程序没有打印hello, 也就是说, myTimerProc没有被调用。 了解Windows消息机制的朋友们可能会知道上面程序的问题, 因此我们打算修改为:

 

 

#include <iostream>
#include <windows.h>
using namespace std;

void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
	cout << "hello" << endl;
}

int main()
{
	MSG msg;
	SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc);

	while(GetMessage(&msg,NULL,NULL,NULL))
	{
		if (msg.message == WM_TIMER) 
		{ 
			TranslateMessage(&msg); 
			DispatchMessage(&msg); 
		} 
	}

	while(1);

	return 0;
}

      这样就好了, 程序每秒打印一次hello world.  但是, 这样的话, 主线程就没法做其他事情了, 只能在循环进行消息处理, 那该怎么办呢? 搞个线程试试, 如下:

 

 

#include <iostream>
#include <windows.h>
using namespace std;

void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
	cout << "hello xxx" << endl;
}


DWORD WINAPI ThreadFun(LPVOID pM)
{
	MSG msg;

	while(GetMessage(&msg,NULL,NULL,NULL))
	{
		if (msg.message == WM_TIMER) 
		{ 
			TranslateMessage(&msg); 
			DispatchMessage(&msg); 
		} 
	}

	return 0;
}


int main()
{
	SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc);

	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
	CloseHandle(handle);

	while(1)
	{
		cout << "world yyyyyy" << endl;
		Sleep(500);
	}

	return 0;
}

     略微意外的是, 仍然没有hello xxx的打印, 且看继续修改的代码:

 

 

#include <iostream>
#include <windows.h>
using namespace std;

void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
	cout << "hello xxx" << endl;
}


DWORD WINAPI ThreadFun(LPVOID pM)
{
	MSG msg;
	SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc);

	while(GetMessage(&msg,NULL,NULL,NULL))
	{
		if (msg.message == WM_TIMER) 
		{ 
			TranslateMessage(&msg); 
			DispatchMessage(&msg); 
		} 
	}

	return 0;
}


int main()
{
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
	CloseHandle(handle);

	while(1)
	{
		cout << "world yyyyyy" << endl;
		Sleep(500);
	}

	return 0;
}

      现在好了, 既有hello xxx,  又有world yyyyyy
 

 

      最后要说明的是, 上述程序有可能会出现线程不同步的问题, 导致打印的结果可能有误。

 

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值