在Windows控制台里画一个时钟

没事学一下C++编程.

效果图:



在用一个线程,不断重画:



头文件:

#include "stdafx.h"
#include <Windows.h>
#include <time.h>
extern "C"
{
	WINBASEAPI HWND WINAPI GetConsoleWindow();
}

class TimeWatch{
public:
	TimeWatch(int x,int y,int radius);
	~TimeWatch();
	void Start();
	void DrawTimeWatch();
private:
	HWND hwnd;
	HDC hdc;
	
	HANDLE hThread;
	DWORD ThreadID;

	int radius;
	int x,y;
	void DrawTimeLine();
	void DrawTimePoint();
};


代码实现:

#include "stdafx.h"
#include "intArray.hpp"
#include <math.h>
#include <iostream>


using namespace std;
TimeWatch::TimeWatch(int x,int y,int radius){
	this->x = x;
	this->y = y;
	this->radius = radius;
}

TimeWatch::~TimeWatch(){

}
#define PAI 3.1415926
#define hourLineLen 30
#define MinuteLineLen 45
#define SecondLineLen 50

void TimeWatch::DrawTimePoint(){
	int count = 12;
	int step = 30;
	int px,py;
	double rad;

	hwnd = GetConsoleWindow();
	hdc = GetDC(hwnd);
	step = 30;
	Ellipse(hdc,x-10-radius,y-10-radius,x+10+radius,y+10+radius);
	int j = 1;
	SetPixel(hdc,x,y,255);

	for(int i = 0;i<360;i+=step){
		rad =2 * PAI * 1 * i / 360;
		px =(int)((cos(rad)*radius));
		py =(int)((sin(rad)*radius));
		SetPixel(hdc,x + px,y + py,255);
	}
}

void TimeWatch::DrawTimeLine(){
	double rad;
	struct tm *ltm;
	time_t now; 
	int minutetime,px,py;
	double hourtimeLineArc,minuteLineArc,senLineArc;
	time(&now);
	//画时钟
	ltm = localtime(&now);
	minutetime = ltm->tm_hour % 12 * 60 + ltm->tm_min;
	hourtimeLineArc = minutetime * 1.0 / (12 * 60) * 360 - 90;
	rad = 2 * PAI * 1 * hourtimeLineArc/360;
	
	px = (int)(cos(rad)*hourLineLen);
	py = (int)(sin(rad)*hourLineLen);
	MoveToEx(hdc,x,y,NULL);
	LineTo(hdc,x+px,y+py);
	//分钟
	minuteLineArc = ltm->tm_min * (360/60) - 90;
	rad = 2 * PAI * 1 * minuteLineArc / 360;
	px = (int)(cos(rad)*MinuteLineLen);
	py = (int)(sin(rad)*MinuteLineLen);
	MoveToEx(hdc,x,y,NULL);
	LineTo(hdc,x+px,y+py);
	//秒
	senLineArc = ltm->tm_sec * (360 / 60) - 90;
	rad = 2 * PAI * 1 * senLineArc / 360;
	px = (int)(cos(rad)*SecondLineLen);
	py = (int)(sin(rad)*SecondLineLen);
	MoveToEx(hdc,x,y,NULL);
	LineTo(hdc,x+px,y+py);
}

void ThreadFunc(TimeWatch *tw){
	while(1){
		tw->DrawTimeWatch();
		Sleep(1000);
	}
}

void TimeWatch::DrawTimeWatch(){
	DrawTimePoint();
	DrawTimeLine();
}
void TimeWatch::Start(){
	hThread = CreateThread(NULL,
		0,
		(LPTHREAD_START_ROUTINE)ThreadFunc,
		(void *)this,
		0,
		&ThreadID);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值