用windows C++实现:当按住键盘Ctrl键同时点击鼠标左键时,正方形填充颜色恢复成默认颜色(白色),位置复原为初始位置(5分)
时间: 2024-01-16 10:05:21 浏览: 175
以下是一个简单的实现。首先,在窗口过程中监听鼠标和键盘事件,当同时按下Ctrl键和鼠标左键时,将正方形位置和颜色恢复为默认值。
```c++
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) {
// 注册窗口类
const wchar_t CLASS_NAME[] = L"myWindowClass";
WNDCLASS wc = { };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// 创建窗口
HWND hWnd = CreateWindowEx(
0,
CLASS_NAME,
L"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 WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static int x = 100, y = 100;
static bool ctrlPressed = false;
static bool leftButtonPressed = false;
switch (message) {
case WM_KEYDOWN:
if (wParam == VK_CONTROL) {
ctrlPressed = true;
}
break;
case WM_KEYUP:
if (wParam == VK_CONTROL) {
ctrlPressed = false;
}
break;
case WM_LBUTTONDOWN:
if (ctrlPressed) {
leftButtonPressed = true;
x = 100;
y = 100;
InvalidateRect(hWnd, NULL, TRUE);
}
break;
case WM_LBUTTONUP:
if (leftButtonPressed) {
leftButtonPressed = false;
InvalidateRect(hWnd, NULL, TRUE);
}
break;
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
HBRUSH brush = CreateSolidBrush(leftButtonPressed ? RGB(255, 0, 0) : RGB(255, 255, 255));
SelectObject(hdc, brush);
Rectangle(hdc, x, y, x + 50, y + 50);
DeleteObject(brush);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
在上面的代码中,我们使用了一个静态变量来保存正方形的位置和当前键盘和鼠标状态。在窗口过程中,我们监听了键盘和鼠标事件,并根据当前状态来更新正方形的位置和颜色。当需要重新绘制窗口时,我们使用 `InvalidateRect` 函数来通知窗口管理器重新绘制窗口。
阅读全文