按要求写c++的windows编程:按下键盘上的ctrl + R键,圆形变为正方形,按下ctrl+C键又变回圆形,如此,可实现圆和正方形间的切换
时间: 2024-02-23 10:01:28 浏览: 75
以下是实现该功能的C++代码:
```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 nCmdShow)
{
const char CLASS_NAME[] = "myWindowClass";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
"My Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
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)
{
static bool isSquare = false;
static HBRUSH hBrush = CreateSolidBrush(RGB(255, 0, 0)); // 红色刷子
static HPEN hPen = CreatePen(PS_SOLID, 5, RGB(0, 0, 0)); // 黑色画笔
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// 创建圆形
if (!isSquare)
{
SelectObject(hdc, hBrush);
SelectObject(hdc, hPen);
Ellipse(hdc, 50, 50, 200, 200);
}
// 创建正方形
else
{
SelectObject(hdc, GetStockObject(WHITE_BRUSH));
SelectObject(hdc, GetStockObject(BLACK_PEN));
Rectangle(hdc, 50, 50, 200, 200);
}
EndPaint(hwnd, &ps);
}
return 0;
case WM_KEYDOWN:
if (GetKeyState(VK_CONTROL) & 0x8000) // 按下Ctrl键
{
if (wParam == 'R') // 按下R键
{
isSquare = true;
InvalidateRect(hwnd, NULL, TRUE); // 重绘窗口
}
else if (wParam == 'C') // 按下C键
{
isSquare = false;
InvalidateRect(hwnd, NULL, TRUE); // 重绘窗口
}
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
```
这个程序创建了一个窗口,按下键盘上的Ctrl + R键会将圆形变为正方形,按下Ctrl + C键又会将正方形变回圆形。实现的关键在于在窗口过程中检测键盘按下事件,并通过InvalidateRect函数重绘窗口来实现形状的切换。
阅读全文