我想在表单级别读取KeyPress事件,但是当DataGridView控件具有焦点时遇到问题:第一个字符触发Form KeyPress事件两次。
以下是一小段代码:
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Enable key preview.
Me.KeyPreview = True
' Create list of elements.
Dim elements As New List(Of TestStuff)({New TestStuff})
' Add datagrid.
Dim dataGridView As New DataGridView
Me.Controls.Add(dataGridView)
dataGridView.Dock = DockStyle.Fill
dataGridView.DataSource = elements
End Sub
Private Sub MainFormView_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
Console.WriteLine(String.Format("KeyPress {0} value: {1}", Now, CStr(e.KeyChar)))
End Sub
End Class
Public Class TestStuff
Public Property Stuff As String
End Class
注意:仅当网格中有元素时才会出现这种情况。
当我运行表单时,不点击任何地方并键入字符,它将触发两次。例如,如果我输入数字“0”两次,我的事件记录显示:
KeyPress 7/18/2017 2:01:57 PM value: 0
KeyPress 7/18/2017 2:01:57 PM value: 0
KeyPress 7/18/2017 2:01:58 PM value: 0
第一次按键0点火两次。如何禁用或绕过此过程?
答案 0 :(得分:1)
在sub的末尾添加e.Handled = true应该可以解决问题