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按钮提示(消息捕获和消息传递)

相关文章
相关标签/搜索