vc++基础班[14]---再论“逃跑”按钮的实现

vc++基础班[14]---再论“逃跑”按钮的实现
------------------------------------------ Begin ----------------------------------------
①、CWnd::GetWindowRect 与 CWnd::GetClientRect 的区别:(获取当前窗口)
GetWindowRect 函数:屏幕坐标系,同时包括窗口的标题栏与边框的大小;
GetClientRect 函数:本身窗口坐标系,左上角坐标始终为(0, 0),不包括窗口标题与边框的大小;

全局的 SDK API 函数:(获取指定窗口)
BOOL GetWindowRect(HWND hWnd, LPRECT lpRect); 与 CWnd::GetWindowRect 同
BOOL GetClientRect(HWND hWnd, LPRECT lpRect); 与 CWnd::GetClientRect 同

备注:在对话框的初始化函数 OnInitDialog() 中调用 GetWindowRect 函数时,得到的窗口左上角坐标也是(0, 0),
是因为系统在创建窗口的时候,先在屏幕的左上角的位置进行创建,之后再移动到屏幕的指定位置。

②、屏幕坐标与窗口坐标的转换:
CWnd::ClientToScreen

void ClientToScreen(
   LPPOINT lpPoint 
) const;
void ClientToScreen(
   LPRECT lpRect 
) const;

CWnd::ScreenToClient

void ScreenToClient(
   LPPOINT lpPoint 
) const;
void ScreenToClient(
   LPRECT lpRect 
) const;
lpPoint
Points to a CPoint object or POINT structure that contains the screen coordinates to be converted.

lpRect
Points to a CRect object or RECT structure that contains the screen coordinates to be converted.



全局的 SDK API 函数:
BOOL ScreenToClient(
  HWND hWnd,        // handle to window
  LPPOINT lpPoint   // screen coordinates
);

BOOL ClientToScreen(
  HWND hWnd,       // handle to window
  LPPOINT lpPoint  // screen coordinates
);

MoveWindow 改变窗口的大小和位置;
SetWindowPos 函数也同样有 MoveWindow 函数的功能,但更灵活,多用于只修改窗口的位置而大小不变或只修改窗口的大小而位置不变的情况

③、“逃跑”按钮的实现

④、要取得 [a, b) 之间的随机整数,使用 (rand()%(b-a))+a (结果值将含a不含b)
在 a=0 的情况下,简写为 rand()%b



主要代码:

01void CMoveButton::OnMouseMove(UINT nFlags, CPoint point)
02{
03    // TODO: Add your message handler code here and/or call default
04    CWnd *pParent = GetParent();
05    CRect parentRect, mRect;
06    pParent->GetClientRect(&parentRect);
07    GetClientRect(&mRect);
08 
09    CRect dstRect;
10    int randX = 0, randY = 0;
11    CPoint pt;
12    GetCursorPos(&pt);
13    ::ScreenToClient(pParent->GetSafeHwnd(), &pt);
14 
15    srand((unsigned)time(0));
16    do{
17        int maxX = parentRect.right-mRect.Width();
18        int minX = parentRect.left;
19        randX = (rand()%(maxX-minX))+minX;
20 
21        int maxY = parentRect.bottom-mRect.Height();
22        int minY = parentRect.top;
23        randY = (rand()%(maxY-minY))+minY;
24        dstRect.SetRect(randX, randY, randX+mRect.Width(), randY+mRect.Height());
25    }while (dstRect.PtInRect(pt));
26 
27    //MoveWindow(dstRect);
28    SetWindowPos(NULL, randX, randY, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
29 
30    CButton::OnMouseMove(nFlags, point);
31}



------------------------------------- End -------------------------------------------

原文链接: vc++基础班[14]---再论“逃跑”按钮的实现 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://www.gyarmy.com/?post=284 )

发表评论

0则评论给“vc++基础班[14]---再论“逃跑”按钮的实现”