Windows API 功能強大,善用它可為 MFC 應用程式增添豐富互動體驗。本文彙整五個實用技巧:游標顯示/隱藏、滑鼠左右鍵交換、取得/設定雙擊時間、滑鼠活動區域限制,附完整 MFC 範例碼。
ShowCursorint ShowCursor(BOOL bShow); // bShow=FALSE 隱藏, TRUE 顯示
// 回傳值:計數器,>=0 顯示,<0 隱藏,初始為 0
void CMyTestDlg::OnHideCursor()
{
int i = ShowCursor(FALSE);
CString str; str.Format(_T("%d"), i);
m_Label.SetWindowText(str);
}
void CMyTestDlg::OnShowCursor()
{
int i = ShowCursor(TRUE);
CString str; str.Format(_T("%d"), i);
m_Label.SetWindowText(str);
}
連續點擊「隱藏」按鈕計數器遞減,達 -1 時游標消失;點擊「顯示」遞增,達 0 時重現。
SwapMouseButtonBOOL SwapMouseButton(BOOL fSwap); // TRUE 交換, FALSE 還原
// 回傳:交換後 TRUE, 還原後 FALSE
void CMyTestDlg::OnReverseMouse()
{
if (SwapMouseButton(TRUE)) MessageBox(_T("左右鍵已交換!"));
}
void CMyTestDlg::OnRestoreMouse()
{
if (!SwapMouseButton(FALSE)) MessageBox(_T("已還原預設!"));
}
交換後需用右鍵點擊「還原」按鈕。
GetDoubleClickTimeUINT GetDoubleClickTime(VOID); // 回傳毫秒數,預設 500ms
void CMyTestDlg::OnGetDoubleClickTime()
{
CString str; str.Format(_T("%d"), GetDoubleClickTime());
m_Label.SetWindowText(str);
}
SetDoubleClickTimeBOOL SetDoubleClickTime(UINT uInterval); // 毫秒數
void CMyTestDlg::OnSetDoubleClickTime()
{
if (SetDoubleClickTime(500)) MessageBox(_T("設定成功!"));
}
ClipCursorBOOL ClipCursor(CONST RECT* lpRect); // lpRect 為螢幕座標矩形
// 解除限制:傳入全螢幕矩形
void CMyTestDlg::OnLockMouse()
{
RECT rc = {10, 10, 200, 200};
if (ClipCursor(&rc)) MessageBox(_T("滑鼠已鎖定於指定區域!"));
}
void CMyTestDlg::OnUnlockMouse()
{
RECT rc = {0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)};
if (ClipCursor(&rc)) MessageBox(_T("滑鼠已解鎖!"));
}
這些 API 操作簡單卻實用,可應用於教學軟體、自助終端機、遊戲輔助工具等場合。所有範例在 Windows 2000 / Visual C++ 6.0 測試通過。