以下代码报错帮我修改#include WindowshLRESULT CALLBACK WindowProcHWND hwnd UINT uMsg WPARAM wParam LPARAM lParam;int WINAPI WinMainHINSTANCE hInstance HINSTANCE hPrevInstance LPSTR lpCmdLine int nShowCmd 创建窗
以下是修改后的代码:
#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
RECT buttonRect = { 100, 100, 200, 150 }; // 将按钮的位置和状态移到全局变量
bool buttonPressed = false;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// 创建窗口
HWND hwnd;
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WindowProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, "MyWindowClass", NULL };
RegisterClassEx(&wc);
hwnd = CreateWindow(wc.lpszClassName, "My Window", WS_OVERLAPPEDWINDOW, 100, 100, 700, 500, NULL, NULL, wc.hInstance, NULL);
// 显示窗口
ShowWindow(hwnd, nShowCmd);
UpdateWindow(hwnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 清理
UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// 绘制设备
HDC hdc;
PAINTSTRUCT ps;
switch (uMsg)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
// 绘制蓝色边框和填充
HPEN hPen = CreatePen(PS_SOLID, 1, RGB(0, 0, 255));
HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 255));
SelectObject(hdc, hPen);
SelectObject(hdc, hBrush);
Rectangle(hdc, buttonRect.left, buttonRect.top, buttonRect.right, buttonRect.bottom);
// 如果按钮被按下,则绘制红色边框和填充
if (buttonPressed)
{
HPEN hRedPen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
HBRUSH hRedBrush = CreateSolidBrush(RGB(255, 0, 0));
SelectObject(hdc, hRedPen);
SelectObject(hdc, hRedBrush);
Rectangle(hdc, buttonRect.left, buttonRect.top, buttonRect.right, buttonRect.bottom);
DeleteObject(hRedPen);
DeleteObject(hRedBrush);
}
DeleteObject(hPen);
DeleteObject(hBrush);
EndPaint(hwnd, &ps);
break;
case WM_LBUTTONDOWN:
// 检查鼠标是否按在按钮上
if (LOWORD(lParam) >= buttonRect.left && LOWORD(lParam) <= buttonRect.right &&
HIWORD(lParam) >= buttonRect.top && HIWORD(lParam) <= buttonRect.bottom)
{
buttonPressed = true;
InvalidateRect(hwnd, &buttonRect, TRUE); // 使按钮区域无效,触发重绘
}
break;
case WM_LBUTTONUP:
// 检查鼠标是否释放在按钮上
if (buttonPressed)
{
buttonPressed = false;
InvalidateRect(hwnd, &buttonRect, TRUE); // 使按钮区域无效,触发重绘
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
修改内容:
- 将
buttonRect和buttonPressed移到全局变量,以便在不同的消息处理函数中共享。 - 将
buttonRect的初始化移到WinMain函数外部。 - 在
WindowProc函数中,移除了对buttonRect和buttonPressed的重复声明和定义
原文地址: https://www.cveoy.top/t/topic/h952 著作权归作者所有。请勿转载和采集!