vulkanino
vulkanino

Reputation: 9134

.NET KeyDown event to handle KeyChars

I made a form representing a numeric keypad, for a touchscreen application, and it contains the keys 0123456789, along with the comma , key. Each key is an instance of a custom control with a property called Key which I set at design time:

   <Browsable(True),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)>
    Private _key As Char
    Property Key As Char
        Get
            Return _key
        End Get
        Set(value As Char)
            _key = value
            Me.Text = _key
        End Set
    End Property

To easily find the pressed key, in the containing form I build a HashSet with all the keys:

Private keys As HashSet(Of Char)
....
For Each c As Control In ...
   keys.Add(...)
Next

Then I listen for the KeyDown event:

AddHandler Me.KeyDown, AddressOf KeyHasBeenPressed

Then in the handler:

Private Sub KeyHasBeenPressed(sender As Object, e As KeyEventArgs)

    If keys.Contains(ChrW(e.KeyValue)) Then
        ' handle the key pressed event...
    End If

End Sub

The problem is with the comma , key. The Key property has been set to , in the designer but at runtime the test keys.Contains fails because e.KeyValue=188 and e.KeyCode=Oemcomma {188}.

What would be the best way to handle this situation? I want to use "special" keys like the comma and maybe the backspace key.

Also consider i8n: my physical numeric keypad shows a dot . but when pressed it must always be treated as a comma , instead.

Upvotes: 1

Views: 1223

Answers (1)

paul
paul

Reputation: 22001

If you use KeyPress rather than KeyDown then you will be able to use the KeyChar property of KeyPressEventArgs which should return a ','

Upvotes: 1

Related Questions