您的位置:首页 > 其它

定时器SetTimer如何用在win32控制台用用程序中

2016-05-16 10:55 489 查看

SetTimer如何用在win32控制台应用程序中

可以使用在main函数中开一个子线程的方法,在子线程中用while(1){}的方式处理定时器的操作

#include <Windows.h>
#include <stdio.h>
#include <conio.h>

VOID CALLBACK TimerProc(
HWND hwnd,     // handle of window for timer messages
UINT uMsg,     // WM_TIMER message
UINT idEvent,  // timer identifier
DWORD dwTime   // current system time
)
{
static int s_count = 0;
printf("WM_TIMER in work thread s_count = %d\n", ++s_count);
}

DWORD CALLBACK Thread(PVOID pvoid)
{
MSG msg;
BOOL bRet;
UINT timerid;

PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
timerid = SetTimer(NULL, 0, 3000, TimerProc);

while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
{
if (bRet == -1)
{
printf("Error:the thread will quit,error id is %d\n", GetLastError());
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(NULL, timerid);
printf("thread end heren");
return 0;
}

int main()
{
HANDLE hThread;

printf("use timer in console application\n");
hThread = CreateThread(NULL, 0, Thread, NULL, 0, NULL);
_getch();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息