在 C++ 中检测 Enter/Return on Keydown 事件

2022-01-12 00:00:00 keypress c++ mfc

我正在尝试在我的应用程序中检测是否按下了 Enter/Return 按钮.我的问题是 LVN_KEYDOWN 事件(表示已按下某个键)没有检测到 Enter/Return 键.

I am trying to detect in my application, if the Enter/Return buttons are pressed. My problem is that the LVN_KEYDOWN event (Indicates that a key has been pressed) does not detect the Enter/Return key.

我已经看到其他语言的类似问题,但找不到 C++ 的解决方案.

I have seen similar questions for other languages, but can not find a solution for C++.

我读取按键的事件是:

void ListOption::OnLvnKeydownList1(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);
    // TODO: Add your control notification handler code here
    if(pLVKeyDow->wVKey == VK_RETURN)
    {
        OnItemActivateList1(pNMHDR, pResult);
        *pResult = 1;
    }
    *pResult = 0;
}

此代码几乎适用于任何键,除了 Enter 键.

This code works for almost any key, execept for the Enter key.

我的对话框只有一个按钮,它的默认按钮"值为 FALSE.如何检测按键?

My dialog has only one button, and it's "Default Button" value is FALSE. How is it possible to detect the keypress?

更新:我的应用程序使用模式对话框.它包含一个包含 CImagePages(tabs) 的 CImageSheet.这是一张可以更好地解释的图片(我放置了灰色块来隐藏一些私人数据).

Update: My application uses modal dialogs.. It contains a CImageSheet that contains CImagePages(tabs). Here is an image to explain better (I have placed grey blocks to hide some private data).

当我按下 Enter 时,我希望打开一个新对话框来更改选项.目前这是通过 LVN_ITEMCTIVATE 事件(当用户双击一个项目时)完成的:

When I press Enter, I wish to open a new dialog to change the option. Currently this is done with the LVN_ITEMCTIVATE event (when the user double clicks an item):

推荐答案

您可以在拥有 ListView 的窗口中覆盖 PreTranslateMessage.在这种情况下,它似乎是一个 CPropertyPage.

You can override PreTranslateMessage in the window which owns the ListView. In this case it seems to be a CPropertyPage.

BOOL CMyPropertyPage::PreTranslateMessage(MSG* pMsg)
{
    //optional: you can handle keys only when ListView has focus
    if (GetFocus() == &List) 
    if (pMsg->message == WM_KEYDOWN)
    {
      if (pMsg->wParam == VK_RETURN)
      {
         //return 1 to eat the message, or allow for default processing
         int sel = List.GetNextItem(-1, LVNI_SELECTED);
         if (sel >= 0)
         {
            MessageBox("VK_RETURN");
            TRACE("ListView_GetNextItem %d
", sel);
            return 1;
         }
         else
            TRACE("ListView_GetNextItem not-selected, %d
", sel);
      }

      if (pMsg->wParam == VK_ESCAPE)
      {
         //do nothing!
      }
    }

    return CPropertyPage::PreTranslateMessage(pMsg);
}

相关文章