您的位置:首页 > 其它

在Win32控制台程序中使用定时器

2016-02-26 18:32 501 查看
定时器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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息