Windows API编程——最简单的窗口程序框架示例

版权声明:转载请注明出处 https://blog.csdn.net/qq_35294564/article/details/82953248

 用Windows API实现一个自定义窗口也需要这么一大堆最基本的程序框架:

#include <windows.h>

static LPCTSTR lpszAppName = "windows API 窗口示例";//窗口名称

HBRUSH hBlueBrush, hRedBrush;//画刷句柄

//响应消息的回调函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//程序的入口
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	MSG            msg;//消息结构
	WNDCLASS       wc;//窗口类型结构
	HWND           hWnd;//窗口句柄

	//创建蓝色和红色画刷用以填充操作
	hBlueBrush = CreateSolidBrush(RGB(0, 0, 255));
	hRedBrush = CreateSolidBrush(RGB(255, 0, 0));

	//定义窗口类型
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = (WNDPROC)WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = NULL;
	wc.hCursor = LoadCursor(NULL, IDC_HAND);

	//使用蓝色画刷填充窗口背景
	wc.hbrBackground = hBlueBrush;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = lpszAppName;

	//注册该窗口类型
	if (RegisterClass(&wc) == 0)
		return false;

	//创建应用程序主窗口
	hWnd = CreateWindow(
		lpszAppName,
		lpszAppName,
		WS_OVERLAPPEDWINDOW,
		100, 100,
		550, 550,
		NULL,
		NULL,
		hInstance,
		NULL
	);
	//如果窗口创建失败,退出程序
	if (hWnd == NULL)
		return false;

	//显示窗口
	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	//启动消息循环,直到窗口被关闭
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		//分发消息至相应的窗口的消息处理回调函数
		DispatchMessage(&msg);
	}

	//程序结束前释放GDI资源
	DeleteObject(hBlueBrush);
	DeleteObject(hRedBrush);

	return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	switch (message) {
		//程序结束
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_PAINT: {
		PAINTSTRUCT ps;
		HBRUSH hOldBrush;

		//开始绘图
		BeginPaint(hWnd, &ps);

		//选用红色刷为当前画刷
		hOldBrush = HBRUSH(SelectObject(ps.hdc, hRedBrush));

		//绘制一个矩形,用当前的红色画刷填充背景
		Rectangle(ps.hdc, 100, 100, 300, 300);

		//恢复以前的画刷状态
		SelectObject(ps.hdc, hOldBrush);

		//结束绘制
		EndPaint(hWnd, &ps);

	}
		break;
	default://将未处理的消息交与Windows默认的处理函数处理
		return(DefWindowProc(hWnd, message, wParam, lParam));
	}

	return(0L);
}

猜你喜欢

转载自blog.csdn.net/qq_35294564/article/details/82953248