MFC之按鍵消息(長按處理) MFC之CToolTipCtrl按鈕提示(消息捕獲和消息傳遞)

想要實現長按鍵的一些控制,查了查能夠經過捕獲鍵盤事件,而後處理按鍵時須要進行的操做。下面簡單的實現左右按鍵界面更新數值加減。html

 1. 重載PreTranslateMessage(MSG* pMsg)函數,在函數中捕獲鍵盤事件並處理響應:函數

BOOL CEditTestDlg::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN)
    {
        if (pMsg->wParam == VK_RIGHT)
        {
            tmp++;
            m_value.Format(_T("%d"),tmp);
            GetDlgItem(IDC_EDIT1)->SetWindowText(m_value);
            return TRUE;
        }
        if (pMsg->wParam == VK_LEFT)
        {
            tmp--;
            m_value.Format(_T("%d"),tmp);
            GetDlgItem(IDC_EDIT1)->SetWindowText(m_value);
            return TRUE;
        }
    }
    return CDialog::PreTranslateMessage(pMsg);
}

 

之前一直使用UpdateData()函數更新,可是此次發現GetDlgItem()更適合如今的狀況,只更新該控件而不會刷新其餘數據。post

2. 以上已經能夠實現,可是若是想調整多久算長按,那能夠經過定時器來實現:this

重載PreTranslateMessage(MSG* pMsg)函數url

BOOL CEditTestDlg::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN)
    {
        this->SetTimer(3,10,NULL);
        m_bKeyDown = TRUE;
        if (pMsg->wParam == VK_RIGHT)
        {
            m_bRight = TRUE;
            return TRUE;
        }
        if (pMsg->wParam == VK_LEFT)
        {
            m_bLeft = TRUE;
            return TRUE;
        }
    }
    else if (pMsg->message == WM_KEYUP)
    {
        m_bRight = FALSE;
        m_bLeft = FALSE;
        m_bKeyDown = FALSE;
        KillTimer(3);
    }
    return CDialog::PreTranslateMessage(pMsg);
}

 

定時器處理:spa

void CEditTestDlg::OnTimer(UINT_PTR nIDEvent)
{
    switch (nIDEvent)
    {
    case 1:
        ……
    case 3:
        if (m_bKeyDown)
        {
            if (m_bLeft)
            {
                tmp--;
                m_value.Format(_T("%d"),tmp);
                GetDlgItem(IDC_EDIT1)->SetWindowText(m_value);
                //UpdateData(FALSE);
            }
            if (m_bRight)
            {
                tmp++;
                m_value.Format(_T("%d"),tmp);
                GetDlgItem(IDC_EDIT1)->SetWindowText(m_value);
                //UpdateData(FALSE);
            }
        }
        break;
    default:
        break;
    }
    CDialog::OnTimer(nIDEvent);
}

 

這樣按鍵響應會更快,可是自帶的定時器精度不夠高,也能夠經過本身實現高精度定時器來控制。code

注意:處理按鍵消息時間之後,須要返回TRUE,否則對話框任然會響應該按鍵消息,至於PreTranslateMessage(MSG* pMsg)對消息的捕獲屏蔽以及返回值的意義見:orm

MFC之CToolTipCtrl按鈕提示(消息捕獲和消息傳遞)

相關文章
相關標籤/搜索