我们说我有3个WinForms
表格A中包含的表格C表格A
在表单C和表单B中,我想捕获KeyUp事件,以便在按下" Escape"时关闭表单。就像这样:
Private Sub formB_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
Select Case e.KeyCode
Case Keys.Escape
Me.Close()
End Select
End Sub
问题是,当我按下" Escape"在表单C中,它还触发表单B中的KeyUp,从而关闭两个表单。表单C看起来像这样,我不得不重写ProcessCmdKey,因此它也可以在该表单上工作。
Private Sub formC_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
Select Case e.KeyCode
Case Keys.Escape
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
e.SuppressKeyPress = True
End Select
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keydata As Keys) As Boolean
If keydata = Keys.Escape Then
OnKeyUp(New KeyEventArgs(keydata))
ProcessCmdKey = True
Else
ProcessCmdKey = MyBase.ProcessCmdKey(msg, keydata)
End If
End Function
我知道我可以简单地将Me.KeyPreview = False放在表格B中,但这样做会阻止Escape Key用于转义表格B.
答案 0 :(得分:0)
在FormB and FormC
中将 KeyPreview 属性设置为 true ,您可以获取 Escape 键:
Private Sub FormC_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then
Me.Close()
End If
End Sub
与 FormB
相同