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
主要代码:
void CMoveButton::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CWnd *pParent = GetParent();
CRect parentRect, mRect;
pParent->GetClientRect(&parentRect);
GetClientRect(&mRect);
CRect dstRect;
int randX = 0, randY = 0;
CPoint pt;
GetCursorPos(&pt);
::ScreenToClient(pParent->GetSafeHwnd(), &pt);
srand((unsigned)time(0));
do{
int maxX = parentRect.right-mRect.Width();
int minX = parentRect.left;
randX = (rand()%(maxX-minX))+minX;
int maxY = parentRect.bottom-mRect.Height();
int minY = parentRect.top;
randY = (rand()%(maxY-minY))+minY;
dstRect.SetRect(randX, randY, randX+mRect.Width(), randY+mRect.Height());
}while (dstRect.PtInRect(pt));
//MoveWindow(dstRect);
SetWindowPos(NULL, randX, randY, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
CButton::OnMouseMove(nFlags, point);
}
------------------------------------- End -------------------------------------------