用c语言完成电子秒表显示器的代码
时间: 2023-06-12 21:08:08 浏览: 101
以下是一个简单的电子秒表显示器的示例代码,使用C语言编写,并使用了Windows API来控制窗口和计时器:
```c
#include <windows.h>
#define TIMER_ID 1
#define TIMER_INTERVAL 10
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
TCHAR szClassName[] = TEXT("Stopwatch");
TCHAR szWindowName[] = TEXT("Stopwatch");
WNDCLASS wndClass = { 0 };
wndClass.lpfnWndProc = WndProc;
wndClass.hInstance = hInstance;
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wndClass.lpszClassName = szClassName;
if (!RegisterClass(&wndClass)) {
MessageBox(NULL, TEXT("Window registration failed!"), szWindowName, MB_ICONERROR);
return 0;
}
HWND hWnd = CreateWindow(szClassName, szWindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 200, NULL, NULL, hInstance, NULL);
if (!hWnd) {
MessageBox(NULL, TEXT("Window creation failed!"), szWindowName, MB_ICONERROR);
return 0;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
MSG msg = { 0 };
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) {
static int hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
switch (message) {
case WM_CREATE:
SetTimer(hWnd, TIMER_ID, TIMER_INTERVAL, NULL);
break;
case WM_TIMER:
milliseconds += TIMER_INTERVAL;
if (milliseconds >= 1000) {
milliseconds -= 1000;
seconds++;
}
if (seconds >= 60) {
seconds -= 60;
minutes++;
}
if (minutes >= 60) {
minutes -= 60;
hours++;
}
InvalidateRect(hWnd, NULL, TRUE);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
TCHAR buffer[50];
wsprintf(buffer, TEXT("%02d:%02d:%02d.%03d"), hours, minutes, seconds, milliseconds);
TextOut(hdc, 10, 10, buffer, lstrlen(buffer));
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
KillTimer(hWnd, TIMER_ID);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
该代码创建了一个窗口,然后使用计时器每10毫秒更新一次窗口,并在窗口中显示一个简单的秒表计时器。使用`hours`,`minutes`,`seconds`和`milliseconds`变量来跟踪经过的时间,然后在`WM_TIMER`消息中更新这些变量,并在`WM_PAINT`消息中使用`TextOut`函数将它们显示在窗口中。
阅读全文