要用C语言实现一个圆形时钟,我们需要使用图形库来绘制图形元素。通过Windows GDI在C语言环境下,使用Windows API在 Visual Studio 中绘制一个圆盘时钟是一个更简便的方法,能看到一个圆盘时钟,小时、分钟和秒钟指针实时更新。

1、新建项目

打开 Visual Studio,文件 -> 新建 -> 项目 -> Visual C++ -> Windows 桌面应用程序,创建一个新的 桌面应用程序项目。如下图,

httpswwwcjavapycom

2、项目代码

项目新建完成后,直接将项目中 “源文件” 文件夹中.cpp文件的内容替换成如下代码:

#include <windows.h>
#include <math.h>
#include <time.h>

HINSTANCE hInst;
HWND hWnd;
constexpr auto M_PI = 3.14159265358979323846;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void DrawClock(HDC hdc, int width, int height);
void DrawHand(HDC hdc, double angle, double length, int width, int height);

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	WNDCLASS wc = { 0 };
	wc.lpfnWndProc = WndProc;
	wc.hInstance = hInstance;
	wc.lpszClassName = TEXT("ClockWindowClass");

	RegisterClass(&wc);

	hWnd = CreateWindow(wc.lpszClassName, TEXT("Analog Clock"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 400, NULL, NULL, hInstance, NULL);

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return (int)msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	switch (message) {
	case WM_PAINT: {
		PAINTSTRUCT ps;
		HDC hdc = BeginPaint(hWnd, &ps);
		RECT rect;
		GetClientRect(hWnd, &rect);
		DrawClock(hdc, rect.right, rect.bottom);
		EndPaint(hWnd, &ps);
	} break;
	case WM_TIMER:
		InvalidateRect(hWnd, NULL, TRUE);
		break;
	case WM_CREATE:
		SetTimer(hWnd, 1, 1000, NULL);
		break;
	case WM_DESTROY:
		KillTimer(hWnd, 1);
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

void DrawClock(HDC hdc, int width, int height) {
	HPEN hPen = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
	SelectObject(hdc, hPen);

	int centerX = width / 2;
	int centerY = height / 2;
	int radius = min(centerX, centerY) - 20;

	Ellipse(hdc, centerX - radius, centerY - radius, centerX + radius, centerY + radius);

	time_t now = time(NULL);
	struct tm *t = localtime(&now);

	double hourAngle = ((t->tm_hour % 12) + t->tm_min / 60.0) * 30.0;
	double minuteAngle = (t->tm_min + t->tm_sec / 60.0) * 6.0;
	double secondAngle = t->tm_sec * 6.0;

	DrawHand(hdc, hourAngle, radius * 0.5, centerX, centerY);
	DrawHand(hdc, minuteAngle, radius * 0.75, centerX, centerY);

	DeleteObject(hPen);
	hPen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
	SelectObject(hdc, hPen);

	DrawHand(hdc, secondAngle, radius * 0.9, centerX, centerY);

	DeleteObject(hPen);
}

void DrawHand(HDC hdc, double angle, double length, int centerX, int centerY) {
	angle = angle - 90;
	double radian = angle * M_PI / 180;
	int xEnd = centerX + (int)(length * cos(radian));
	int yEnd = centerY + (int)(length * sin(radian));
	MoveToEx(hdc, centerX, centerY, NULL);
	LineTo(hdc, xEnd, yEnd);
}

运行效果:

httpswwwcjavapycom

推荐文档

相关文档

大家感兴趣的内容

随机列表