在Win32控制檯程序中使用定時器

定時器Timer,是編程中最常用的功能之一,在VC MFC中,定時器功能很好實現,例程也很多,那麼在黑漆漆的Win32 Console窗口中如何實現呢?

方法有二,一是使用多媒體時鐘來計時,二是用傳統Timer只不過需要自己傳消息。下面分別貼代碼。

1.多媒體時鐘

#include"stdlib.h"
#pragma comment(lib,"Winmm.lib")

void CALLBACK TimerProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
{
	printf("Timer\n");

}
void main()
{
	MMRESULT nIDTimerEvent = timeSetEvent(1000, 0, TimerProc, 0, (UINT)TIME_PERIODIC);
	while (1);
}



2.SetTimer

/*Timer process function*/
void CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
        printf("timer\n");
}

/*main function*/
void main()
{
	SetTimer(NULL, 1, 1000, TimerProc);
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (msg.message == WM_TIMER)
		{
			DispatchMessage(&msg);
		}
	}
}


3.線程中使用,在網上看到過類似的東西,不嫌麻煩或者另有他用可以試試:

VOID CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
	printf("timer\n");
}

DWORD CALLBACK Thread(PVOID   pvoid)
{
	MSG  msg;
	PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	UINT  timerid = SetTimer(NULL, 1, 1000, TimerProc);
	BOOL  bRet;


	while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
	{
		if (bRet == -1)
		{
			//   handle   the   error   and   possibly   exit   
		}
		else
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	KillTimer(NULL, timerid);
	printf("thread end here\n");
	return   0;
}

void main()
{
	DWORD   dwThreadId; 	
	HANDLE  hThread = CreateThread(NULL, 0, Thread, 0, 0, &dwThreadId);
	while (1);
}



4.直接用多線程取代定時器

DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
	while(1)
	{
		printf("thread 1\n");
		Sleep(1000);
	}
	return 0;
}

void main()
{
	HANDLE hThread;
	hThread = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	while(1);
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章