在窗口中显示一个球,该球以与水平成45度夹角作直线运动,当遇到边界时,反弹回来,仍与水平成45度角继续运动。
#include<windows.h>
#include<stdlib.h>
#include<string.h>
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
//主函数
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
HWND hwnd;
MSG Msg;
WNDCLASS wndclass;
char lpszClassName[]="boll";
char lpszTitle[]="123";
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_CROSS);
wndclass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);//窗口背景为白色
wndclass.lpszMenuName=NULL; //窗口中无菜单
wndclass.lpszClassName=lpszClassName;
if( !RegisterClass( &wndclass))
{
MessageBeep(0);return FALSE;
}
hwnd = CreateWindow
(
lpszClassName,
lpszTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&Msg,NULL,0,0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
LRESULT CALLBACK WndProc
(HWND hwnd,UINT iMessage,UINT wParam,LONG IParam)
{
HDC hDC;
HBRUSH hBrush;
HPEN hPen;
PAINTSTRUCT PtStr;
RECT rect;
static int x=100,y=100,xd=2,yd=2;
switch(iMessage)
{
case WM_PAINT:
hDC=BeginPaint(hwnd,&PtStr);
hPen=CreatePen(PS_SOLID,2,RGB(255,0,0));
SelectObject(hDC,hPen);
hBrush=CreateSolidBrush(RGB(255,255,0));
SelectObject(hDC,hBrush);
GetClientRect(hwnd,&rect);
Ellipse(hDC,x-10,y-10,x+10,y+10);
x+=xd;y+=yd;
if(x-10<0||x+10>rect.right)
xd=-xd;
if(y-10<0||y+10>rect.bottom)
yd=-yd;
DeleteObject(hPen);
DeleteObject(hBrush);
EndPaint(hwnd,&PtStr);
Sleep(10);
InvalidateRect(hwnd,NULL,1);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd,iMessage,wParam,IParam);
}
return 0;
}