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
|
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
static HBRUSH b1;
int RectWidth = 105;
int RectHeight = 50;
static RECT r1 = {}, client = {}; //technically the client rect does not need to be static
static RECT DefPos ={}; //The Default rect position in the window
int x;
int y;
int p = rand() % 1000;
int q = rand() % 1000;
int move = 10;
switch (message)
{
case WM_CREATE:
{
COLORREF c1 = RGB (140, 0, 140);
b1 = CreateSolidBrush (c1);
//Initialise the rectangle default position
GetClientRect (hwnd, &client);
DefPos.left = client.left + 390;
DefPos.right = (client.left + client.right) /2 + RectWidth;
DefPos.top = client.top + 300;
DefPos.bottom = (client.top + client.bottom) /2 - RectHeight;
//Copy default position to R1 also;
r1 = DefPos;
return 0;
}
case WM_PAINT:
hdc = BeginPaint( hwnd, &ps );
//Paint the rectangle
FillRect (hdc, &r1, b1);
EndPaint(hwnd,&ps);
return 0;
case WM_MOUSEMOVE:
x = LOWORD (wParam);
y = HIWORD (wParam);
if(x == r1.left)
{
r1.left += p;
}
if(x == r1.right)
{
r1.left -= p;
}
if(y == r1.top)
{
r1.top += q;
}
if(y == r1.bottom)
{
r1.top -= q;
}
return 0;
case WM_KEYDOWN:
switch (wParam)
{
case VK_LEFT:
r1.left -= move;
r1.right -= move;
break;
case VK_RIGHT:
r1.left += move;
r1.right += move;
break;
case VK_UP:
r1.top -= move;
r1.bottom -= move;
break;
case VK_DOWN:
r1.top += move;
r1.bottom += move;
break;
case VK_ESCAPE:
r1 = DefPos;
break;
}
InvalidateRect(hwnd,NULL,TRUE);
UpdateWindow(hwnd);
return 0;
case WM_SIZE:
return 0;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
}
return DefWindowProc (hwnd, message, wParam, lParam);
}
|