处理系统键关闭消息时禁用烦人的声音

Disable annoying sound when handling syskeydown message

本文关键字:声音 消息 处理系统      更新时间:2023-10-16

嗨,我已经编写了自己的自定义控件,从 MFC CEdit 重写。为此,我需要覆盖SYS_KEY_UP和SYS_KEY_DOWN。但是,每次控件处理这些消息时,都会听到烦人的声音,就好像输入无效或其他什么一样。有谁知道是什么产生了声音以及如何禁用它。

更新代码

// CShotcutEdit
class CShortcutEdit : public CEdit
{
    DECLARE_DYNAMIC(CShortcutEdit)
public:
    CShortcutEdit();
    virtual ~CShortcutEdit();
protected:
    DECLARE_MESSAGE_MAP()
    afx_msg UINT OnGetDlgCode();
    afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg void OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
    virtual BOOL PreTranslateMessage(MSG* pMsg);
    virtual void DoDataExchange(CDataExchange* pDX);
    virtual void PreSubclassWindow();
    virtual void OnChar(UINT uiChar, UINT uiCount, UINT uiFlags);
    // ... Other Members

};
// ShotcutEdit.cpp : implementation file
//
#include "stdafx.h"
#include "GridPlus.h"
#include "ShortcutEdit.h"

// CShotcutEdit
IMPLEMENT_DYNAMIC(CShortcutEdit, CEdit)
CShortcutEdit::CShortcutEdit()
{
}
CShortcutEdit::~CShortcutEdit()
{
}

BEGIN_MESSAGE_MAP(CShortcutEdit, CEdit)
    ON_WM_GETDLGCODE()
    ON_WM_KEYDOWN()
    ON_WM_SYSKEYDOWN()
    ON_WM_SYSKEYUP()
    ON_WM_KEYUP()
    ON_WM_CHAR()
END_MESSAGE_MAP()
UINT CShortcutEdit::OnGetDlgCode()
{
    return DLGC_WANTARROWS | DLGC_WANTALLKEYS | DLGC_WANTCHARS;
}
void CShortcutEdit::DoDataExchange(CDataExchange* pDX)
{
    CEdit::DoDataExchange(pDX);
}
BOOL CShortcutEdit::PreTranslateMessage(MSG* pMsg)
{
    return CEdit::PreTranslateMessage(pMsg);
}
void CShortcutEdit::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
}
void CShortcutEdit::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // ... Check for Alt or F10 and translate to string;
}
void CShortcutEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // .. Check for Ctrl Shift and translate to string
}
void CShortcutEdit::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    SetWindowText(L"The desired shortcut is..."); // Should print "alt+f10" for example
}
void CShortcutEdit::OnChar(UINT uiChar, UINT uiCount, UINT uiFlags)
{
}

void CShortcutEdit::PreSubclassWindow()
{
    HideCaret();
    CEdit::PreSubclassWindow();
}
// CShotcutEdit message handlers

这是编辑控件的默认行为。记事本在响应 Alt+A 键时执行相同的操作。

为避免声音,过载PreTranslateMessage

BOOL CShortcutEdit::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_SYSKEYDOWN)
    {
        UINT nFlags = HIWORD(pMsg->lParam);
        int nChar = (int)pMsg->wParam;
        if (nChar == 'A' && nFlags & KF_ALTDOWN)
        {
            TRACE("ALT+A Keyn");
            return 1;
        }
    }
    return CEdit::PreTranslateMessage(pMsg);
}
此外,如果您不需要编辑控件,

则不要使用编辑控件,而不是使用编辑控件并破坏每个输入。

您可能需要 CHotKeyCtrl