現代瀏覽器(如 Opera、MyIE2)支援滑鼠手勢:按住右鍵拖曳特定軌跡即可觸發前進、後退、關閉分頁等指令。本文示範如何在 MFC 對話框專案中實作核心辨識邏輯,程式碼改編自共享軟體聯盟「小樹衝浪瀏覽器」。
BOOL m_bIsCapture; // 是否已捕捉滑鼠
char m_MouseGestures[4]; // 記錄手勢序列(U/D/L/R)
char m_SeqMG[4]; // 觸發比對用序列
int m_iMGLen, m_iMouseGS, m_iMouseGE;
POINT m_StartPoint; // 起始座標
OnMouseMove)偵測右鍵按下並捕捉滑鼠,呼叫 MoveDirection() 判斷四個基本方向:
if (nFlags == MK_RBUTTON) {
if (m_bIsCapture) {
m_bIsCapture = FALSE;
SetCapture();
m_StartPoint = point;
}
char dir;
if (MoveDirection(point, &dir)) {
PushMouseGesture(dir);
m_StartPoint = point;
}
}
MoveDirection)計算位移向量 (x, y),若距離平方 > 64 則判定方向:
BOOL MoveDirection(CPoint &point, char *Direction) {
int x = point.x - m_StartPoint.x;
int y = point.y - m_StartPoint.y;
int dist = x*x + y*y;
if (dist > 64) {
if (x > abs(y) && x > 0) *Direction = 'R';
else if (abs(x) > abs(y) && x < 0) *Direction = 'L';
else if (y > abs(x) && y > 0) *Direction = 'D';
else if (abs(y) > abs(x) && y < 0) *Direction = 'U';
else return FALSE;
return TRUE;
}
return FALSE;
}
PushMouseGesture)循環緩衝區避免重複相同方向,更新頭尾索引。
OnRButtonUp)將緩衝區序列轉為字串,比對預設手勢對應表:
"D" -> "Down"
"L" -> "Left"
"U" -> "Up"
"R" -> "Right"
"UD" -> "Up Down"
"RLR" -> "Right Left Right"
"UL" -> "Up Left"
"UR" -> "Up Right"
開發者可自行擴充手勢與指令對應。文件檢視架構程式同理可移植。