前情回顾:
在讲述了WINDOWS编程的梗概后,作者讲解WINDOWS的匈牙利命名法体系,WINDOWS结构和窗口建立,接着进一步讲解了WINDOW的深入点的用法,WINDOWS的消息机制及应用,GDI介绍和资源(.RC)使用。
第四章要点:
1.GDI进阶。
如何用GDI画点,线,面。 GDI的概念是,模拟真实的画画,先创建笔和刷子,笔用来勾勒,刷子用来上色,再想画什么,然后勾出来上色。
例:
hdc = GetDC(hwnd);
color = RGB(rand()%256,rand()%256,rand()%256);
color_pen = CreatePen(PS_SOLID,10,color);
color_brush = CreateSolidBrush(color);
//erase
SelectObject(hdc,bg_brush);
SelectObject(hdc,bg_pen);
Ellipse(hdc,rect_ellipse.left,rect_ellipse.top,rect_ellipse.right,rect_ellipse.bottom);
MoveToEx(hdc,0,0,NULL);
LineTo(hdc,point.x,point.y);
Rectangle(hdc,rect.left,rect.top,rect.right,rect.bottom);
//draw
SelectObject(hdc,color_brush); //init
SelectObject(hdc,color_pen);
SetRect(&rect,400,0,400+rand()%401,rand()%401);
SetRect(&rect_ellipse,0,400,rand()%401,400+rand()%401);
point.x = rand()%401; point.y = rand()%401;
MoveToEx(hdc,0,0,NULL); //line
LineTo(hdc,point.x,point.y);
Rectangle(hdc,rect.left,rect.top,rect.right,rect.bottom); //FillRect(hdc,&rect,color_brush);
Ellipse(hdc,rect_ellipse.left,rect_ellipse.top,rect_ellipse.right,rect_ellipse.bottom); //ellipse
for(int i=0;i<5;++i){
poly[i].x = 400+rand()%401;
poly[i].y = 400+rand()%401;
}
Polygon(hdc,poly,5);
Sleep(400);
DeleteObject(color_brush);
DeleteObject(color_pen);
ReleaseDC(hwnd,hdc);
SelectObject(hdc,FONT); 函数为文本设置样式 ,FONT表示什么样式,可以用FONT=GetStockObject来或者自带FONT,也可以用FONT=CreatFont来自定义。
3.定时
介绍了两种定时方法
1).WM_TIMER消息
设置一个timer,SetTimer(hwnd,id,delay,fn);
timer会每隔delay的时间发送一个WM_TIMER的消息,并自动执行回调函数fn。可以将自己想执行的任务房子WM_TIMER后,也可以放在fn中。
2).GetTickCount()
返回当然计时。
例:
start_time = GetTickCount();
while(true){
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){
if(msg.message == WM_QUIT) break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
//game
hdc = GetDC(hwnd);
if(GetTickCount()-start_time>33){
Colorful(hdc,hwnd);
start_time = GetTickCount();
}
}
控件也就是窗口,只不过是输入父窗口的子窗口。它有自己的窗口属性,句柄函数,会发送WM_COMMAND消息。
通过SendMessage(hwnd,message,wparam,lparam)向控件发送消息,以操控控件。
5.获取消息
我们想知道自己的程序在怎么样一个电脑上跑,是在一个老爷机上跑,还是在Alient上跑,是在大屏幕液晶上跑,还是在学校机房上跑。
那么就需要获取信息。
有大量的函数来告诉你相关信息,如
int width = GetSystemMetrics(SM_CXSCREEN);//返回屏幕宽度
GetTextMetrics(hdc,lptextmetris);//获取字体信息
6.T3D游戏控制台程序
讲解了一个游戏框架:
WinMain{
CreateWindow()
Init()
----------loop
game()
----------------
gameover()
}