1. 程式人生 > >Windows程式設計之生成一個簡單的完整的視窗

Windows程式設計之生成一個簡單的完整的視窗

#include <windows.h>

//視窗過程回撥函式
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(
	HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nShowCmd)
{
	HWND hwnd;//視窗控制代碼
	MSG msg;//訊息
	WNDCLASS wc;//視窗類

	//1.設計一個視窗類
	wc.style = 0;
	wc.lpfnWndProc = (WNDPROC)WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "MyWndClass";

	//2.註冊視窗類
	RegisterClass(&wc);

	//3.建立視窗
	hwnd = CreateWindow(
		TEXT("MyWndClass"),
		TEXT("Hello SDK Application"),
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		NULL,//父視窗控制代碼
		NULL,//視窗選單控制代碼
		hInstance,
		NULL);

	//4.顯示和更新視窗
	ShowWindow(hwnd, nShowCmd);
	UpdateWindow(hwnd);

	//5.訊息迴圈
	while (GetMessage(&msg,NULL,0,0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);//轉發到視窗過程
	}

	return msg.wParam;
}

LRESULT CALLBACK WndProc(
	HWND hwnd,
	UINT message,
	WPARAM wParam,
	LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;//DC控制代碼
	RECT rect;

	//對各種訊息進行處理
	switch (message)
	{
	case WM_SIZE:
		//重畫paint
		return 0;
	case WM_LBUTTONDOWN://滑鼠左鍵按下
		//MessageBox(hwnd, TEXT("Mouse Clicked!"), TEXT("message"),MB_OK);
		//PostQuitMessage(0);
		return 0;
	case WM_PAINT://繪製訊息
		hdc = BeginPaint(hwnd, &ps);
		GetClientRect(hwnd, &rect);
		//Ellipse(hdc, 0, 0, 200, 100);
		DrawText(hdc, TEXT("Hello Windows!"), -1, &rect,
			DT_SINGLELINE | DT_CENTER | DT_VCENTER);
		EndPaint(hwnd, &ps);
		return 0;

	case WM_DESTROY://銷燬視窗訊息(關閉)
		PostQuitMessage(0);
		return 0;
	default:
		break;
	}
	return DefWindowProc(hwnd, message, wParam, lParam);
}

執行結果: