首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

滑鼠手勢辨識實作:以右鍵拖曳觸發指令

     編輯:關於C++

現代瀏覽器(如 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"

開發者可自行擴充手勢與指令對應。文件檢視架構程式同理可移植。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved