第八章 计时器(BEEPER2)

时间:2022-11-22 09:28:12
第八章 计时器(BEEPER2)第八章 计时器(BEEPER2)
 1 /*-------------------------------------
 2 BEEPER2.C -- Timer Demo Program No.1
 3              (c) Charles Petzold, 1998
 4 -------------------------------------*/
 5 
 6 #include <Windows.h>
 7 
 8 #define ID_TIMER 1
 9 
10 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
11 VOID CALLBACK TimerPorc(HWND, UINT, UINT, DWORD);
12 
13 int WINAPI WinMain( __in HINSTANCE hInstance
14                     , __in_opt HINSTANCE hPrevInstance
15                     , __in LPSTR lpCmdLine
16                     , __in int nShowCmd )
17 {
18     static TCHAR szAppName[] = TEXT("Bepper2");
19     HWND hwnd;
20     MSG msg;
21     WNDCLASS wndclass;
22 
23     wndclass.style = CS_HREDRAW | CS_VREDRAW;
24     wndclass.lpfnWndProc = WndProc;
25     wndclass.cbClsExtra = 0;
26     wndclass.cbWndExtra = 0;
27     wndclass.hInstance = hInstance;
28     wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
29     wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
30     wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
31     wndclass.lpszMenuName = NULL;
32     wndclass.lpszClassName = szAppName;
33 
34     if (!RegisterClass(&wndclass))
35     {
36         MessageBox(NULL, TEXT("Program requires Windows NT!")
37             , szAppName, MB_ICONERROR);
38         return 0;
39     }
40 
41     hwnd = CreateWindow(szAppName, TEXT("Beeper1 Timer Demo")
42         , WS_OVERLAPPEDWINDOW
43         , CW_USEDEFAULT, CW_USEDEFAULT
44         , CW_USEDEFAULT, CW_USEDEFAULT
45         , NULL, NULL, hInstance, NULL);
46 
47     ShowWindow(hwnd, nShowCmd);
48     UpdateWindow(hwnd);
49 
50     while (GetMessage(&msg, NULL, 0, 0))
51     {
52         TranslateMessage(&msg);
53         DispatchMessage(&msg);
54     }
55 
56     return msg.wParam;
57 }
58 
59 LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
60 {
61     switch (message)
62     {
63     case WM_CREATE:
64         SetTimer(hwnd, ID_TIMER, 1000, TimerPorc);
65         return 0;
66 
67     case WM_DESTROY:
68         KillTimer(hwnd, ID_TIMER);
69         PostQuitMessage(0);
70         return 0;
71     }
72 
73     return DefWindowProc(hwnd, message, wParam, lParam);
74 }
75 
76 VOID CALLBACK TimerPorc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
77 {
78     static BOOL fFlipFlop = FALSE;
79     HBRUSH hBrush;
80     HDC hdc;
81     RECT rc;
82 
83     MessageBeep(-1);
84     fFlipFlop = !fFlipFlop;
85 
86     GetClientRect(hwnd, &rc);
87 
88     hdc = GetDC(hwnd);
89     hBrush = CreateSolidBrush(fFlipFlop ? RGB(255, 0, 0) : RGB(0, 0, 255));
90     FillRect(hdc, &rc, hBrush);
91     ReleaseDC(hwnd, hdc);
92     DeleteObject(hBrush);
93 }
BEEPER2.C