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

来源:互联网 发布:系统架构图 软件 编辑:程序博客网 时间:2024/05/16 19:17

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;}
0 0
原创粉丝点击