编写一个基于Win32 API 的时钟程序,显示当前系统日期时间
时间: 2023-06-10 12:07:05 浏览: 103
下面是一个基于Win32 API的时钟程序的代码,它可以显示当前系统日期和时间:
```c++
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("Clock");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
// 初始化窗口类
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
// 注册窗口类
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"),
szAppName, MB_ICONERROR);
return 0;
}
// 创建窗口
hwnd = CreateWindow(szAppName, TEXT("Clock"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
// 显示窗口
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
// 消息循环
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static int cxClient, cyClient;
static HFONT hFont;
static TCHAR szTime[9], szDate[13];
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
SYSTEMTIME st;
switch (message)
{
case WM_CREATE:
// 创建字体
hFont = CreateFont(48, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
TEXT("Arial"));
SetTimer(hwnd, 1, 1000, NULL); // 创建计时器
return 0;
case WM_SIZE:
// 更新窗口大小
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_TIMER:
// 更新时间
GetLocalTime(&st);
wsprintf(szTime, TEXT("%02d:%02d:%02d"), st.wHour, st.wMinute, st.wSecond);
wsprintf(szDate, TEXT("%04d/%02d/%02d"), st.wYear, st.wMonth, st.wDay);
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_PAINT:
// 绘制时钟
hdc = BeginPaint(hwnd, &ps);
SelectObject(hdc, hFont);
SetTextAlign(hdc, TA_CENTER | TA_TOP);
SetBkMode(hdc, TRANSPARENT);
// 绘制日期和时间
rect.left = 0;
rect.top = cyClient / 2;
rect.right = cxClient;
rect.bottom = cyClient / 2 + 60;
DrawText(hdc, szTime, -1, &rect, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
rect.left = 0;
rect.top = cyClient / 2 + 60;
rect.right = cxClient;
rect.bottom = cyClient / 2 + 120;
DrawText(hdc, szDate, -1, &rect, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
// 销毁字体和计时器
KillTimer(hwnd, 1);
DeleteObject(hFont);
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
```
该程序使用了`CreateWindow`函数创建一个名为"Clock"的窗口,并在`WM_CREATE`消息处理程序中创建了一个计时器以每秒更新时间。在`WM_TIMER`处理程序中,程序获取当前系统时间并将其格式化为字符串形式,然后调用`InvalidateRect`函数以触发窗口重绘。在`WM_PAINT`处理程序中,程序绘制日期和时间字符串。在窗口关闭时,程序销毁计时器和字体对象。
阅读全文