判断鼠标是否点击矩形,点击到矩形就变色,要怎么改?help
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL PtInRect(
_In_ const RECT* lprc, //矩形区域
_In_ POINT pt //当前点
);
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow)
{
static TCHAR szAppName[] = TEXT("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = TEXT("MyClass");
if (!RegisterClass(&wndclass))//(注册窗口类的API是RegisterClass)
{
MessageBox(NULL, TEXT("RegisterClass fail!"), szAppName, MB_ICONERROR);
return 0;
}
//窗口起始位置(100,100),大小300*400
hwnd = CreateWindow(
TEXT("MyClass"), // window class name
szAppName, // window caption
WS_OVERLAPPEDWINDOW, // window style
100, // initial x position
100, // initial y position
630, // initial x size
520, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // creation parameters
if (!hwnd)
{
MessageBox(NULL, TEXT("CreateWindow fail!!"), szAppName, MB_ICONERROR);
return 0;
}
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
HPEN hOldPen, hPen1;
static HBRUSH hBrush, hBrushR;
switch (message)
{
case WM_CREATE:
hBrush = (HBRUSH)GetStockObject(BLACK_BRUSH);
hBrushR = CreateSolidBrush(RGB(255, 0, 0));
return 0;
case WM_LBUTTONDOWN:
{
pt.x = LOWORD(lParam); //当前鼠标位置
pt.y = HIWORD(lParam); //当前鼠标位置
if (PtInRect(&hdc, pt)) { //点击检测函数
hBrush = hBrushR;
break;
}
}break;
case WM_LBUTTONUP: // 鼠标左键,抬起时刷新
InvalidateRect(hwnd, NULL, FALSE);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
hPen1 = CreatePen(HS_CROSS, 5, RGB(0, 0, 225));
SelectObject(hdc, hBrush);
//将hPen1选入设备环境
hOldPen = (HPEN)SelectObject(hdc, hPen1);
Rectangle(hdc, 50, 50, 150, 150);
//删除创建的画刷
DeleteObject(hBrush);
//删除创建的画笔
DeleteObject(hPen1);
//释放设备环境
EndPaint(hwnd, &ps);
return 0;
//恢复设备环境,将默认画笔选回
SelectObject(hdc, hOldPen);
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
hdc = GetDC(hwnd);
ReleaseDC(hwnd, hdc);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}