1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <windows.h>
int rectX = 50; int rectY = 50; int rectWidth = 50; int rectHeight = 30;
BOOL isRectSelected = FALSE; POINT offset;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
Rectangle(hdc, rectX, rectY, rectX + rectWidth, rectY + rectHeight);
EndPaint(hwnd, &ps); } break;
case WM_LBUTTONDOWN: { int mouseX = LOWORD(lParam); int mouseY = HIWORD(lParam);
if (mouseX >= rectX && mouseX <= rectX + rectWidth && mouseY >= rectY && mouseY <= rectY + rectHeight) { isRectSelected = TRUE; offset.x = mouseX - rectX; offset.y = mouseY - rectY; }
InvalidateRect(hwnd, NULL, TRUE); } break;
case WM_LBUTTONUP: { isRectSelected = FALSE; } break;
case WM_MOUSEMOVE: { if (isRectSelected) { int mouseX = LOWORD(lParam); int mouseY = HIWORD(lParam);
rectX = mouseX - offset.x; rectY = mouseY - offset.y;
InvalidateRect(hwnd, NULL, TRUE); }
TRACKMOUSEEVENT tme; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE; tme.hwndTrack = hwnd; TrackMouseEvent(&tme);
SetTimer(hwnd, 1, 100, NULL); } break;
case WM_TIMER: { POINT pt; GetCursorPos(&pt); ScreenToClient(hwnd, &pt); RECT clientRect; GetClientRect(hwnd, &clientRect); if (pt.x < 0 || pt.x >= clientRect.right || pt.y < 0 || pt.y >= clientRect.bottom) { isRectSelected = FALSE; InvalidateRect(hwnd, NULL, TRUE); } } break;
case WM_MOUSELEAVE: { isRectSelected = FALSE; InvalidateRect(hwnd, NULL, TRUE); } break;
case WM_DESTROY: KillTimer(hwnd, 1); PostQuitMessage(0); return 0;
default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { const char CLASS_NAME[] = "Sample Window Class";
WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx( 0, CLASS_NAME, "Rectangle Control Example", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 400, NULL, NULL, hInstance, NULL );
ShowWindow(hwnd, nShowCmd);
MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); }
return 0; }
|