我已经在窗体和表单的keydown上启用了KeyPreview选项,我正在检测Escape keydown以弹出一个msgbox,询问用户是否要退出应用程序。
但问题是,我有一个文本框需要在Escape按键上清除其内容,而不是询问用户是否需要退出。我尝试在此控件上使用keydown事件,但是表单keydown事件发生在控件keydown之前(我希望这反过来发生)。
文本框上的代码
Private Sub txtAmount(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtAmount.KeyDown
If e.KeyCode = Keys.Escape Then
'//Escape keypress
MsgBox("TEXTBOX ESCAPE")
sender.Text = ""
End If
End Sub
主菜单表单上使用的代码
Private Sub frmMainMenu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then Application.Exit()
End Sub
我无法使用previewkeydown因为MaskTextBox没有引发previewkeydown事件..
答案 0 :(得分:2)
检查txtAmount是否集中在Form_KeyDown中:
Private Sub txtAmount_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtAmount.KeyDown
If e.KeyCode = Keys.Escape Then
'//Escape keypress
MsgBox("TEXTBOX ESCAPE")
sender.Text = ""
End If
End Sub
Private Sub frmMainMenu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If txtAmount.Focused Then Return
If e.KeyCode = Keys.Escape Then Application.Exit()
End Sub
修改:或者,如果您不想单独指定每个控件,可以按类型执行:
If TypeOf Me.ActiveControl Is MaskTextBox Then Return
甚至更简单,将Form_KeyDown-Event更改为KeyUp事件。
Public Class frmMainMenu
Private KeyHandled As Boolean
Private Sub txtAmount_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtAmount.KeyDown
If e.KeyCode = Keys.Escape Then
sender.Text = ""
KeyHandled = True
End If
End Sub
Private Sub frmMainMenu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
KeyHandled = False
End Sub
Private Sub frmMainMenu_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If KeyHandled Then Return
If e.KeyCode = Keys.Escape Then Application.Exit()
End Sub
End Class
答案 1 :(得分:1)
这是我的代码
Private Sub When_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown, MyBase.KeyDown
If sender.name = "Your form name" Then
If e.KeyCode = Keys.Escape And Not TextBox1.Focused Then
MsgBox("me")
End If
ElseIf sender.name = "your textBox name" Then
If e.KeyCode = Keys.Escape Then
MsgBox("txt")
End If
End If
End Sub
我希望这可以帮到你