作者:朱金燦
來源:https://blog.csdn.net/clever101
在windows環境下控制檯程序上創建時鐘,需要手動建立一個消息循環,這個消息循環,可以在主線程裏建立,也可以在子線程中建立,參考代碼如下:
/**
* @file ConsoleTimer.cpp
* @brief 測試在windows環境下控制檯程序上創建時鐘
* @details
* @author 朱金燦
* @date 2019年9月14日
* @version 1.0.0.1
* @par Copyright (c):DreamStudio
* @par History:
*/
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <sys/timeb.h>
char datestr[16];
char timestr[16];
char mss[4];
void log(char *s) {
struct tm *now;
struct timeb tb;
ftime(&tb);
now = localtime(&tb.time);
sprintf(datestr, "%04d-%02d-%02d", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
sprintf(timestr, "%02d:%02d:%02d", now->tm_hour, now->tm_min, now->tm_sec);
sprintf(mss, "%03d", tb.millitm);
printf("%s %s.%s %s", datestr, timestr, mss, s);
}
VOID CALLBACK TimerProc(
HWND hwnd, // handle of window for timer messages
UINT uMsg, // WM_TIMER message
UINT_PTR idEvent, // timer identifier
DWORD dwTime // current system time
)
{
static int s_count = 0;
log("In TimerProc \n");
}
DWORD CALLBACK Thread(PVOID pvoid)
{
MSG msg;
BOOL bRet;
UINT timerid;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
timerid = SetTimer(NULL, 0, 1000, 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 here");
return 0;
}
/*
在主線程中建立消息循環
*/
void CommonMethod()
{
int i;
MSG msg;
SetTimer(NULL, 0, 1000, TimerProc);
for (i = 0; i < 20; i++)
{
if (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
/*
使用子線程的方式
*/
void UseThread()
{
HANDLE hThread;
printf("use timer in console application\n");
hThread = CreateThread(NULL, 0, Thread, NULL, 0, NULL);
}
int main() {
// CommonMethod();
UseThread();
getchar();
return 0;
}
以上代碼在64位Win7,VS2015上編譯通過,效果圖如下:
參考文獻: