Steph M
Steph M

Reputation: 31

KeyPress fires twice on Form when DataGridView focused

I want to read the KeyPress event on the form level but am running into a problem when a DataGridView control has focus: The first character fires the Form KeyPress event twice.

Here is a small sample of code:

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

Note: This only occurs when there are elements within the grid.

When I run the form, without clicking anywhere and type in a character, it will fire twice. For instance, if I type the numeric "0" two times, my event logging shows:

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

With the first keypress of 0 firing twice. How can I disable or get around this process?

Upvotes: 1

Views: 843

Answers (1)

Alessandro Mandelli
Alessandro Mandelli

Reputation: 581

Apparently this is a bug which has been around for awhile. Please check https://social.msdn.microsoft.com/Forums/windowsapps/en-US/734d6c7a-8da2-48c6-9b3d-fa868b4dfb1d/c-textbox-keydown-triggered-twice-in-metro-applications?forum=winappswithcsharp&forum=winappswithcsharp

Adding e.Handled = true at the end of your sub should do the trick

Upvotes: 2

Related Questions