C语言全局时钟(Windows程序设计 第五版 )

#include 

#define ID_TIMER 1

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	TCHAR szAppName[20] = TEXT("Beeper1");
	HWND hwnd;
	MSG msg;
	WNDCLASS CLS;

	CLS.style			= CS_HREDRAW | CS_VREDRAW;
	CLS.lpfnWndProc		= WndProc;
	CLS.cbClsExtra		= 0;
	CLS.cbWndExtra		= 0;
	CLS.hInstance		= hInstance;
	CLS.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	CLS.hCursor			= LoadCursor(NULL, IDC_ARROW);
	CLS.hbrBackground   = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
	CLS.lpszMenuName	= NULL;
	CLS.lpszClassName	= szAppName;

	if (!RegisterClass(&CLS))
	{
		MessageBox(NULL, TEXT("时钟测试"), TEXT("提示"), MB_ICONERROR);
		return 0;
	}

	hwnd = CreateWindow(
		szAppName,
		TEXT("时钟测试"),
		WS_OVERLAPPEDWINDOW,
		0,//CW_USEDEFAULT,
		0,//CW_USEDEFAULT,
		200,//CW_USEDEFAULT,
		150,//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 BOOL fFlipFlop = FALSE;
	HBRUSH hBrush;
	HDC hdc;
	PAINTSTRUCT ps;
	RECT rc;
	int ScreenX, ScreenY;

	switch (message)
	{
	case WM_CREATE:
		//启动时钟ID_TIMER
		SetTimer(hwnd, ID_TIMER, 1000, NULL);
		//获取窗口的RECT
		GetClientRect(hwnd, &rc);
		//获取屏幕的宽度
		ScreenX = GetSystemMetrics(SM_CXSCREEN);
		//获取屏幕的高度
		ScreenY = GetSystemMetrics(SM_CYSCREEN);
		//将窗口居中显示
		MoveWindow(hwnd, (ScreenX - (rc.right - rc.left)) / 2, (ScreenY - (rc.bottom - rc.top)) / 2, (rc.right - rc.left), rc.bottom - rc.top, FALSE);
		//SetWindowPos(hwnd, NULL, (GetSystemMetrics(SM_CXSCREEN) - (rc.right - rc.left)) / 2, (GetSystemMetrics(SM_CYSCREEN) - (rc.bottom - rc.top)) / 2, (rc.right - rc.left), rc.bottom - rc.top, NULL);
		return 0;
	case WM_TIMER:
		//发声
		MessageBeep(MB_ICONINFORMATION);
		fFlipFlop = !fFlipFlop;
		//使整个客户区失效
		InvalidateRect(hwnd, NULL, FALSE);
		return 0;
	case WM_PAINT:
		//获取失效区域,以开始绘制失效区域
		hdc = BeginPaint(hwnd, &ps); 
		//获取窗口的RECT
		GetClientRect(hwnd, &rc);
		//创建画刷
		hBrush = CreateSolidBrush(fFlipFlop ? RGB(255,0,0) : RGB(0,0,255));
		//用指定画刷填充矩形区域
		FillRect(hdc, &rc, hBrush);
		//结束绘制
		EndPaint(hwnd, &ps);
		//释放画刷
		DeleteObject(hBrush);
		return 0;
	case WM_DESTROY:
		//终止时钟ID_TIMER
		KillTimer(hwnd, ID_TIMER);
		//关闭窗口
		PostQuitMessage(0);
		return 0;
	}
	//--其他消息使用默认处理方式
	return DefWindowProc(hwnd, message, wParam, lParam);
}

你可能感兴趣的:(C)