创建win32窗口程序

本文指导如何使用Visual Studio 2022创建一个简单的Windows桌面应用,从新建空项目到绘制基本窗口和文本。通过WinProc回调函数实现窗口事件处理,包括WM_PAINT和WM_DESTROY消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

VS2022 选择Windows桌面向导-选择桌面应用程序-空项目

输入代码

#include <Windows.h>
#include <iostream>

using namespace std;

const string ProgramTitle = "Hello Windows";

// The window event callback function
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wPrarm, LPARAM lParam)
{
	RECT drawRect;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_PAINT:
	{
		// start drawing
		hdc = BeginPaint(hWnd, &ps);
		for (int i = 0; i < 20; i++)
		{
			int x = i * 20;
			int y = x;
			drawRect = { x,y,x + 100,y + 20 };
			DrawTextA(hdc, ProgramTitle.c_str(), ProgramTitle.length(), &drawRect, DT_CENTER);
		}
		// stop drawing
		EndPaint(hWnd, &ps);
		break;
	}
	case WM_DESTROY:
	{
		PostQuitMessage(0);
		break;
	}
	}
	return DefWindowProcA(hWnd, message, wPrarm, lParam);
}

// Helper function to set up the window properties
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	// set the new window's properties
	WNDCLASSEX wc;
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = (WNDPROC)WinProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = NULL;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszClassName = ProgramTitle.c_str();
	wc.lpszMenuName = NULL;
	wc.hIconSm = NULL;
	return RegisterClassEx(&wc);
}

// Helper function to create the window and refersh it
bool InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	// create a new window
	HWND hWnd = CreateWindow(
		ProgramTitle.c_str(),// className
		ProgramTitle.c_str(),// windowName
		WS_OVERLAPPEDWINDOW,// style
		CW_USEDEFAULT, CW_USEDEFAULT,// position of window
		640, 480,// window size
		NULL,// parent window (not used)
		NULL,// meun (not used)
		hInstance,// application instance
		NULL);// window parameters (not used)

	// was there an error creating the window?
	if (hWnd == 0)
		return 0;
	// display the window
	ShowWindow(hWnd, nCmdShow);
	// raise the paint event
	UpdateWindow(hWnd);
	return 1;
}

// Entry point for a windows program
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
	// create the window
	MyRegisterClass(hInstance);
	if (!InitInstance(hInstance, nShowCmd))
		return 0;
	// main message loop
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return msg.wParam;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值