Win32 API(也称为Windows API)是Windows比较原生态的C++ API。
使用的编辑器是Visio Studio 2019。
创建项目完毕,在源文件文件夹下,右键,添加,新建项,选择C++文件,命名为main.cpp:
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Register the window class
WNDCLASS wc = {};
wc.hInstance = hInstance;
wc.lpszClassName = L"MainWindow";
wc.lpfnWndProc = WindowProc;
wc.hbrBackground = (HBRUSH)(GetStockObject(GRAY_BRUSH));
RegisterClass(&wc);
// Create the window
HWND hwnd = CreateWindow(
L"MainWindow", // Window class name
L"窗口名称", // Window name
WS_OVERLAPPEDWINDOW, // Window style
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, // Size and position
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
// Show the window
ShowWindow(hwnd, nShowCmd);
// Run the message loop
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
【F7】生成解决方案
【Ctrl+F5】开始执行
运行结果如下:
知识点
第一个窗口程序,就包含了比较多的C++知识。
LRESULT:实际类型是长整型long
HWND:Handle of Window,窗口的句柄
在字符串前加一个L表示将ANSI字符串转换成Unicode的字符串,即每个字符占用两个字节。
CALLBACK和WINAPI,实际都是__stdcall,也就是函数调用方式,通常有__stdcall和__cdecl两种方式。