在控制台程序上创建时钟的做法

作者:朱金灿

来源: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上编译通过,效果图如下:

参考文献:

  1. 定时器SetTimer如何用在win32控制台用用程序中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

clever101

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值