注册Window窗体类:RegisterClass
//定义窗口类
WNDCLASS wndClass;
//窗口类样式
wndClass.style = CS_HREDRAW | CS_VREDRAW;
//窗口过程函数
wndClass.lpfnWndProc = MyWndDef;
//窗口类无扩展
wndClass.cbClsExtra = 0;
//窗口实例无扩展
wndClass.cbWndExtra = 0;
//窗口所属实例句柄
wndClass.hInstance = hInstance;
//窗口最小化图标句柄
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
//窗口光标样式句柄
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
//窗口背景句柄
wndClass.hbrBackground = (HBRUSH)(GetStockObject(WHITE_BRUSH));
//窗口类Menu名称
wndClass.lpszMenuName = NULL;
//窗口类的唯一名称
wndClass.lpszClassName = L"hello";
if (!RegisterClass(&wndClass)) {
MessageBox(NULL, L"窗口类注册失败!", L"提示", MB_OK);
return FALSE;
}
创建Window窗体句柄:CreateWindow
HWND hwnd = CreateWindow(L"hello",//窗口类名称
L"第一个窗口程序",//窗口左上角的标题
WS_OVERLAPPEDWINDOW,//窗口风格
CW_USEDEFAULT,//窗口左上角坐标
CW_USEDEFAULT,
CW_USEDEFAULT,//窗口宽高
CW_USEDEFAULT,
NULL,//父窗口句柄
NULL,//窗口菜单句柄
hInstance,//窗口所属实例句柄
NULL
);
显示窗体和更新窗体
//显示窗口
ShowWindow(hwnd, nCmdShow);
//绘制用户区域
UpdateWindow(hwnd);
自定义窗口过程函数
LRESULT CALLBACK MyWndDef(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
处理Window消息
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
完整代码
// TestWin.cpp : 定义应用程序的入口点。
//
#include <windows.h>
#include "TestWin.h"
LRESULT CALLBACK MyWndDef(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
//定义窗口类
WNDCLASS wndClass;
//窗口类样式
wndClass.style = CS_HREDRAW | CS_VREDRAW;
//窗口过程函数
wndClass.lpfnWndProc = MyWndDef;
//窗口类无扩展
wndClass.cbClsExtra = 0;
//窗口实例无扩展
wndClass.cbWndExtra = 0;
//窗口所属实例句柄
wndClass.hInstance = hInstance;
//窗口最小化图标句柄
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
//窗口光标样式句柄
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
//窗口背景句柄
wndClass.hbrBackground = (HBRUSH)(GetStockObject(WHITE_BRUSH));
//窗口类Menu名称
wndClass.lpszMenuName = NULL;
//窗口类的唯一名称
wndClass.lpszClassName = L"hello";
if (!RegisterClass(&wndClass)) {
MessageBox(NULL, L"窗口类注册失败!", L"提示", MB_OK);
return FALSE;
}
HWND hwnd = CreateWindow(L"hello",//窗口类名称
L"第一个窗口程序",//窗口左上角的标题
WS_OVERLAPPEDWINDOW,//窗口风格
CW_USEDEFAULT,//窗口左上角坐标
CW_USEDEFAULT,
CW_USEDEFAULT,//窗口宽高
CW_USEDEFAULT,
NULL,//父窗口句柄
NULL,//窗口菜单句柄
hInstance,//窗口所属实例句柄
NULL
);
//显示窗口
ShowWindow(hwnd, nCmdShow);
//绘制用户区域
UpdateWindow(hwnd);
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}