自己封装一个win32窗口框架
笔者自己封装了一个win32窗口框架,为便于后续的代码重用,将其写成博客。
首先是头文件:
#pragma once
#include <Windows.h>
class CMyWnd
{
public:
CMyWnd(HINSTANCE hInstance, TCHAR *szClassName);
~CMyWnd();
BOOL Create(const TCHAR *szTitle, DWORD dwWidth, DWORD dwHeight,
DWORD dwStyle = WS_OVERLAPPEDWINDOW);
void Show(DWORD dwCmdShow = SW_SHOW);
int Run();
protected:
bool RegisterWndClass();
static LRESULT CALLBACK s_WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
virtual void OnCommand(WPARAM wParam);
protected:
HWND m_hWnd;
HINSTANCE m_hInstance;
TCHAR *m_szMyWndClassName;
};
然后是.cpp文件:
#include "CMyWnd.h"
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
// ———————————public————————————
CMyWnd::CMyWnd(HINSTANCE hInstance, TCHAR *szClassName)
: m_hInstance(hInstance), m_szMyWndClassName(szClassName)
{
}
CMyWnd::~CMyWnd()
{
}
BOOL CMyWnd::Create(const TCHAR *szTitle, DWORD dwWidth, DWORD dwHeight, DWORD dwStyle)
{
if (!RegisterWndClass())
return FALSE;
m_hWnd = CreateWindowEx(
0, m_szMyWndClassName, szTitle, dwStyle, CW_USEDEFAULT,
CW_USEDEFAULT, dwWidth, dwHeight, nullptr, nullptr, m_hInstance, this);
return (m_hWnd != nullptr);
}
void CMyWnd::Show(DWORD dwCmdShow)
{
ShowWindow(m_hWnd, dwCmdShow);
UpdateWindow(m_hWnd);
}
int CMyWnd::Run()
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
// ———————————–protected———————————-
bool CMyWnd::RegisterWndClass()
{
WNDCLASSEX wndclass = {0};
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = CMyWnd::s_WndProc;
wndclass.hInstance = m_hInstance;
wndclass.hCursor = LoadCursor(nullptr, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wndclass.lpszClassName = m_szMyWndClassName;
return (RegisterClassEx(&wndclass) != 0);
}
LRESULT CMyWnd::s_WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
CMyWnd *pThis = nullptr;
if (uMsg == WM_NCCREATE)
{
CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
pThis = reinterpret_cast<CMyWnd *>(pCreate->lpCreateParams);
pThis->m_hWnd = hwnd;
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));
}
else
{
pThis = reinterpret_cast<CMyWnd *>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
}
if (pThis)
{
return pThis->WndProc(uMsg, wParam, lParam);
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
LRESULT CMyWnd::WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(m_hWnd, uMsg, wParam, lParam);
}
void CMyWnd::OnCommand(WPARAM wParam)
{
}
这个框架具有一定的可拓展性,可以用继承该类并添加更多的功能。
![第5章,[Win32 章节] :边框绘制函数(六)-171主机测评](https://www.171host.com/wp-content/uploads/2026/08/20260822144238-6a89b55eb002b-220x150.png)

