vb.net 当按钮处于焦点时如何防止回车键触发点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20643435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:11:21  来源:igfitidea点击:

How to prevent the enter key from triggering a click event when a button is in focus

vb.netvisual-studio-2012enterkeycode

提问by Samsung_74

I'm trying to make a program which can accept button based inputs as well as keyboard based inputs which it then outputs to a text box. However I would like to use the Enter key to trigger the function to output to the text box. However since there are buttons on the form. They will be triggered like a mouse click event when the enter key is pressed. I need to find a way to either make the enter key only trigger the event I want and not to trigger the button. Or I need to find a way to make the buttons never have focus and for the focus always to be on the form itself while still having the buttons be clickable. Any help?

我正在尝试制作一个程序,它可以接受基于按钮的输入以及基于键盘的输入,然后将其输出到文本框。但是我想使用 Enter 键触发函数输出到文本框。但是,由于表单上有按钮。当按下回车键时,它们将像鼠标单击事件一样被触发。我需要找到一种方法来使回车键只触发我想要的事件而不触发按钮。或者我需要找到一种方法让按钮永远不会有焦点,并且焦点总是在表单本身上,同时仍然让按钮可以点击。有什么帮助吗?

       If e.KeyCode = Keys.Enter Then
        SecondNum = Val(TB_Output.Text)
        ResultEquals()
        TB_Output.Text = Result
    End If

采纳答案by Neolisk

Theoretically, setting KeyPreviewproperty of the form to Trueshould do it. Then handle KeyDownevent, and make sure to set e.Handledto Trueon pressing the Enter key (or e.SuppressKeyPress, depends on implementation of controls you are working with).

理论上,将KeyPreview表单的属性设置为True应该这样做。然后处理KeyDown事件,并确保在按下 Enter 键时设置e.HandledTrue(或 e. SuppressKeyPress,取决于您正在使用的控件的实现)。

I tried this approach in a sample project just now, however, and it did not work with a button for some reason. You may need to resort to using WndProcon the form level, this always works 100%.

然而,我刚刚在一个示例项目中尝试了这种方法,但由于某种原因它不适用于按钮。您可能需要WndProc在表单级别使用,这总是 100% 有效。

回答by CalfordMath

If you want to go right to the heart of the key events, and intercept even the arrows and other focus-changing keys, you'll need something like this:

如果你想直接进入关键事件的核心,甚至拦截箭头和其他改变焦点的键,你需要这样的东西:

Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                'your logic here
                Return True  'this surpresses any default action
        End Select
        Return MyBase.ProcessDialogKey(keyData) 'this allows the default action to be processed for any cases you haven't explicitly intercepted

    End Function