第八章 8-2 数字时钟

时间:2022-05-11 23:33:51

第八章 8-2 数字时钟
1,获取当前时间 GetLocalTime

SYSTEMTIME st;
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

GetLocalTime(&st);

2,数字时钟实例

#define ID_TIMER 1
//根据窗口坐标,整个数字应该是倒过来
void DisplayDigit(HDC hdc, int iNumber)
{
static BOOL fSevenSegment[10][7] = {
1,1,1,0,1,1,1,//0
0,0,1,0,0,1,0,//1
1,0,1,1,1,0,1,//2
1,0,1,1,1,0,1,//3
0,1,1,1,0,1,0,//4
1,1,0,1,0,1,1,//5
1,1,0,1,1,1,1,//6
1,0,1,0,0,1,0,//7
1,1,1,1,1,1,1,//8
1,1,1,1,0,1,1,//9
};
//规划每一个数字8
static POINT ptSegment[7][6] = {
7,6,11,2,31,2,35,6,31,10,11,10,
6,7,10,11,10,31,6,35,2,31,2,11,
36,7,40,11,40,31,36,35,32,31,32,11,
7,36,11,32,31,32,35,36,31,40,11,40,
6,37,10,41,10,61,6,65,2,61,2,41,
36,37,40,41,40,61,36,65,32,61,32,41,
7,66,11,62,31,62,35,66,31,70,11,70
};
int iSeg;
for(iSeg = 0;iSeg < 7 ;iSeg++)
{
if (fSevenSegment[iNumber][iSeg])
Polygon(hdc, ptSegment[iSeg], 6);

}



}

//显示两个数字
void DisplayTwoDigits(HDC hdc, int iNumber)
{
DisplayDigit(hdc, iNumber / 10);
OffsetWindowOrgEx(hdc, -42, 0, NULL);
DisplayDigit(hdc, iNumber % 10);
OffsetWindowOrgEx(hdc, -42, 0, NULL);


}

//显示数字中间的冒号
void DisplayColon(HDC hdc)
{
POINT ptColon[2][4] = { 2,21,6,17,10,21,6,25,
2,51,6,47,10,51,6,55

};
Polygon(hdc, ptColon[1], 4);
Polygon(hdc, ptColon[0], 4);
OffsetWindowOrgEx(hdc, -12, 0, NULL);


}
//数字时钟显示当前的时间
void DisplayTime(HDC hdc)
{
SYSTEMTIME st;
GetLocalTime(&st);//获取当前系统的时间

DisplayTwoDigits(hdc, st.wHour);
DisplayColon(hdc);
DisplayTwoDigits(hdc, st.wMinute);
DisplayColon(hdc);
DisplayTwoDigits(hdc, st.wSecond);


}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HBRUSH hBrushRed;
RECT rect;

static int cxClient, cyClient;
switch (message)
{
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
break;
case WM_CREATE:
hBrushRed = CreateSolidBrush(RGB(255, 0, 0));
SetTimer(hWnd, ID_TIMER, 1000, NULL);
break;
case WM_TIMER:
InvalidateRect(hWnd, NULL,TRUE);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: 在此处添加使用 hdc 的任何绘图代码...

/* DisplayTwoDigits(hdc, 17);
DisplayColon(hdc);
DisplayTwoDigits(hdc, 40);
*/

//使用映射模式映射到整个窗口
SetMapMode(hdc, MM_ISOTROPIC);
SetWindowExtEx(hdc, 276, 72, NULL);
SetViewportExtEx(hdc, cxClient, cyClient, NULL);

//改变视口和窗口的坐标原点
SetViewportOrgEx(hdc, cxClient/2, cyClient/2, NULL);
SetWindowOrgEx(hdc, 138, 36, NULL);
//选择画笔和话刷
SelectObject(hdc, GetStockObject(NULL_PEN));
SelectObject(hdc, hBrushRed);
DisplayTime(hdc);

EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
DeleteObject(hBrushRed);
KillTimer(hWnd, ID_TIMER);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}