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;
}