Disable beep of enter and escape key c#

大城市里の小女人 提交于 2019-11-26 11:36:33

问题


I want to disable the beep sound that i get when i press enter in a textbox. My KeyDown event is:

 private void textBox_Zakljucak_KeyDown(object sender, KeyEventArgs e)
        {

            if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))
            {
                Parent.SelectNextControl(textBox_Zakljucak, true, true, true, true);
            }
            else if ((e.KeyCode == Keys.Back))
            {
                textBox_Zakljucak.Select(textBox_Zakljucak.Text.Length, 0);
            }
            else if (!Regex.IsMatch(textBox_Zakljucak.Text, @\"^[0-9.-]+$\"))
            {
                textBox_Zakljucak.Clear();
                textBox_Zakljucak.Select(textBox_Zakljucak.Text.Length, 0);
            }
    }

回答1:


You have to prevent the KeyPressed event from being generated, that's the one that beeps. That requires setting the SuppressKeyPress property to true. Make that look similar to:

        if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))
        {
            Parent.SelectNextControl(textBox_Zakljucak, true, true, true, true);
            e.Handled = e.SuppressKeyPress = true;
        }



回答2:


If you want to prevent the event from bubbling up in Winforms or WPF/Silverlight, you need to set e.Handled to true from within the event handler.

Only do this if you have actually handled the event to your satisfaction and do not want any further handling of the event in question.




回答3:


this works for me.

private void txtTextbox_KeyDown(object sender, KeyEventArgs e)
{
    //do somthing

    if(e.KeyCode==Keys.Enter)
    {
        e.Handled=true;
        e.SuppressKeyPress=true;
    }
}

private void txtTextbox_KeyUp(object sender, KeyEventArgs e)
{
    e.Handled=false;
    e.SuppressKeyPress=false;
}



回答4:


    private void txtMessage_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.KeyCode == Keys.Enter)
        {
            e.SuppressKeyPress = true;
            _sendMessage.PerformClick();
        } 
    }       



回答5:


Running VS 2015 here and the above answers did not work for me. In order to suppress the beep on a hard return (in both textboxes and checkboxes), I switched from the KeyDown event to the KeyPress event and did the following:

private void mTxtSrchStr1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
         this.sSearchFind();
         e.Handled = true;
    }
}

There is no e.SuppressKeyPress in the KeyPress event, but it is not needed there.




回答6:


Just set the Form KeyPreview property to true, then add the following code to The Form KeyPress event;

if (e.KeyChar == (char)Keys.Return)

 e.Handled = true;

then bye the bip!!!



来源:https://stackoverflow.com/questions/13952932/disable-beep-of-enter-and-escape-key-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!