#include <windows.h> float x = 100.0f; // 球的中心点X坐标 float y = 100.0f; // 球的中心点Y坐标 float speed = 10.0f; // 球响应按钮后的初始速度 float friction = 0.99f; // 球与地面的摩擦系数 float dx = 0.0f; // X轴增量 float dy = 0.0f; // Y轴增量 LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow) { WNDCLASS wc; MSG msg; HWND hWnd; if( !hPrevInstance ) { wc.lpszClassName = "GenericAppClass"; wc.lpfnWndProc = MainWndProc; wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW; wc.hInstance = hInstance; wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = (HBRUSH)( COLOR_WINDOW+1 ); wc.lpszMenuName = "GenericAppMenu"; wc.cbClsExtra = 0; wc.cbWndExtra = 0; RegisterClass( &wc ); } hWnd = CreateWindow( "GenericAppClass", "Happy Ball", WS_OVERLAPPEDWINDOW & (~WS_MAXIMIZEBOX) & (~WS_THICKFRAME), 100, 100, 800, 600, NULL, NULL, hInstance, NULL ); ShowWindow( hWnd, nCmdShow ); while( GetMessage( &msg, NULL, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } return msg.wParam; } LRESULT CALLBACK MainWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static PAINTSTRUCT ps; static HDC hDC; static HBRUSH hBrush; static RECT rect; GetClientRect(hwnd, &rect); const int nRadius = 16; switch (message) { case WM_CREATE: SetTimer(hwnd, 1, 5, NULL); hBrush = CreateSolidBrush(RGB(0,0,0)); return 0; case WM_PAINT: hDC = BeginPaint(hwnd, &ps); SelectObject(hDC, hBrush); Ellipse(hDC, x - nRadius, y - nRadius, x + nRadius, y + nRadius); EndPaint(hwnd, &ps); break; case WM_KEYDOWN: switch (wParam) { case VK_UP: dy -= speed; break; case VK_DOWN: dy += speed; break; case VK_LEFT: dx -= speed; break; case VK_RIGHT: dx += speed; break; } break; case WM_TIMER: dx *= friction; dy *= friction; x += dx; y += dy; if (x > rect.right - nRadius) { x = (rect.right - nRadius) - (x - (rect.right - nRadius)); dx = -dx; } if (x < nRadius) { x = nRadius + nRadius - x; dx = -dx; } if (y > rect.bottom - nRadius) { y = rect.bottom - nRadius - (y - (rect.bottom - nRadius)); dy = -dy; } if (y < nRadius) {y = nRadius + nRadius - y; dy = -dy; } InvalidateRect(hwnd, &rect, TRUE); break; case WM_DESTROY: KillTimer(hwnd, 1); DeleteObject(hBrush); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }