VB.net - 检测是否有人点击“f5”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20144973/
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 15:56:19  来源:igfitidea点击:

VB.net - Detecting if someone clicks "f5"

vb.net

提问by Hymanz

I am trying to make a Visual Basic program, and I want it if you click F5, the program's current form refreshes.

我正在尝试制作一个 Visual Basic 程序,如果您单击 F5,我想要它,该程序的当前窗体将刷新。

I mostly just need to code to detect if someone clicks the key "F5"

我主要只需要编写代码来检测是否有人点击了“F5”键

I've tried below, but any keys refresh it then.

我在下面尝试过,但是任何键都会刷新它。

Private Sub LoginBox_KeyDown(sender As Object, e As EventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.F5 Then
       Me.Close
       Loginbox.show
    Else
       'Do nothing
      End If
End Sub

EDIT: Both John Koerner and Nadeem_MK have the right answers.

编辑:John Koerner 和 Nadeem_MK 都有正确的答案。

I used Nadeem's for the sub and then used the Closing method from John Koerner.

我将 Nadeem 用于 sub,然后使用了 John Koerner 的 Closing 方法。

I can only have one be the answer... But thanks anyways! Last time didn't go far.

我只能有一个答案......但还是谢谢你!上次没走多远。

I asked this before... but "somehow" people didn't understand this very basic question.

我之前问过这个……但是“不知何故”人们不理解这个非常基本的问题。

回答by Nadeem_MK

I've just tested it in VS2008 and it seem to me that the Form event of KeyPress, Keydown and KeyUp do not trigger on button press.
To do so, you need to put the Me.KeyPreview = Trueon FormLoad() and then proceed;

我刚刚在 VS2008 中对其进行了测试,在我看来,KeyPress、Keydown 和 KeyUp 的 Form 事件不会在按下按钮时触发。
为此,您需要将Me.KeyPreview = TrueFormLoad()放在上面,然后继续;

Private Sub Form_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Form.KeyDown

        If e.KeyData = Keys.F5 Then
            Me.Refresh()
        End If

End Sub

回答by John Koerner

In order to catch certain key presses, you need to set KeyPreview = True. Also, if this is the only form open in your app and you close it, then your app will close completely when you call Me.Close(), so you need to show the new form before you close the old one.

为了捕捉某些按键,您需要设置 KeyPreview = True。此外,如果这是您的应用程序中打开的唯一表单并且您将其关闭,那么当您调用 Me.Close() 时,您的应用程序将完全关闭,因此您需要在关闭旧表单之前显示新表单。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.KeyPreview = True
End Sub


Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.F5 Then
        Me.Hide()
        Dim f As New Form1
        f.ShowDialog()
        Me.Close()
    End If
End Sub