/*********************************
简单的版权声明
作者:WinGame_D
时间:2010-2-24
用时:6小时
效果:一个色彩渐变的球体在窗口中运动,遇到边界发生碰撞
适用学习人群:windows程序设计初学者(高手勿笑话我的粗浅的设计)
以下代码只用于学习,请勿转载
*********************************/
//windowsAPI.h代码段
#pragma once
#include <windows.h>
//碰撞测试函数,发生碰撞将改变球体运动方向
void SetPointDirect(HWND hWnd,RECT &GRect,POINT &DirectPoint)
{
RECT rect;
GetClientRect(hWnd,&rect);
RECT newRect;
newRect.top=GRect.top+DirectPoint.y;
newRect.bottom=GRect.bottom+DirectPoint.y;
newRect.left=GRect.left+DirectPoint.x;
newRect.right=GRect.right+DirectPoint.x;
if(newRect.top<rect.top || newRect.bottom>rect.bottom)
{
DirectPoint.y=0-DirectPoint.y;
}
if(newRect.left<rect.left || newRect.right>rect.right)
{
DirectPoint.x=0-DirectPoint.x;
}
GRect.top=GRect.top+DirectPoint.y;
GRect.bottom=GRect.bottom+DirectPoint.y;
GRect.left=GRect.left+DirectPoint.x;
GRect.right=GRect.right+DirectPoint.x;
}
//windowsAPI.cpp代码段
#include <windows.h>
#include <crtdbg.h>
#include <tchar.h>
#include "windowsAPI.h"
LRESULT CALLBACK WinProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
HDC hdc;
static HDC DrawHDC; //全局的兼容DC,作用是在后台这个DC上画好,然后画好的东西让hdc显示
static HBITMAP DrawBitmap; //全局的兼容位图
HPEN newpen;
HBRUSH newbrush;
static RECT mCircle={0,0,200,200}; //圆的大小
static POINT Direction={5,2}; //运动方向
static int x=0,y=0,z=0; //色彩RGB分量
static int m=1,n=2,o=3; //色彩分量的改变度
switch(message)
{
case WM_TIMER:
hdc=GetDC(hWnd);
BitBlt(DrawHDC,0,0,800,600,hdc,0,0,WHITENESS);
newpen=CreatePen(PS_SOLID,3,RGB(x,y,z));
SelectObject(DrawHDC,newpen);
newbrush=CreateSolidBrush(RGB(x,y,z));
SelectObject(DrawHDC,newbrush);
x=x+m;
y=y+n;
z=z+o;
if(x+m>255 || x+m<0)
{
m=-m;
}
if(y+n>255 || y+n<0)
{
n=-n;
}
if(z+o>255 || z+o<0)
{
o=-o;
}
SetPointDirect(hWnd,mCircle,Direction);
Ellipse(DrawHDC,mCircle.left,mCircle.top,mCircle.right,mCircle.bottom);
BitBlt(hdc,0,0,800,600,DrawHDC,0,0,SRCCOPY);
DeleteObject(newpen);
DeleteObject(newbrush);
ReleaseDC(hWnd,hdc);
break;
case WM_CREATE:
{
SetTimer(hWnd,1,20,NULL);
hdc=GetDC(hWnd);
DrawHDC=CreateCompatibleDC(hdc);
DrawBitmap=CreateCompatibleBitmap(hdc,800,600);
SelectObject(DrawHDC,DrawBitmap);
ReleaseDC(hWnd,hdc);
}
break;
case WM_PAINT:
break;
case WM_DESTROY:
KillTimer(hWnd,1);
DeleteObject(DrawBitmap);
ReleaseDC(hWnd,DrawHDC);
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
WNDCLASS wc={0};
wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpfnWndProc=WinProc;
wc.hInstance=hInstance;
wc.lpszClassName=_T("DeskProtect");
wc.style=CS_HREDRAW | CS_VREDRAW ;
RegisterClass(&wc);
HWND hWnd=CreateWindow(_T("DeskProtect"),_T("WinDeskPro"),WS_BORDER | WS_CAPTION | WS_SYSMENU ,50,50,800,600,NULL,NULL,hInstance,NULL);
_ASSERTE(hWnd!=0);
ShowWindow(hWnd,nShowCmd);
UpdateWindow(hWnd);
MSG msg={0};
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}