Cobold
Cobold

Reputation: 2613

Change textbox input

I want to allow the user to enter symbols using the keyboard. I'm checking the textbox onkeydown event for the pressed key and then change it to a symbol, for example if I would press 'a' then the textbox would show '☺'. But the problem is that the textbox shows both 'a' and '☺'. Is there a better event to check this, or better way to do this?

Private Sub TextBox_KeyDown(sender as object, e as keyeventargs) handles TextBox.KeyDown
  Select Case e.key
    Case 'a'
      TextBox.text += '☺'
    End Select
End Sub

Upvotes: 3

Views: 140

Answers (2)

rsbarro
rsbarro

Reputation: 27359

Try using the KeyPress event. In that event handler, you'll want to set the Handled property of the KeyPressEventArgs to true to keep the a key from getting added to the textbox.

Private Sub TextBox_KeyPress(sender as object, e as KeyPressEventArgs) handles TextBox.KeyPress
  Select Case e.key
    Case 'a'
      TextBox.text += '☺'
      e.Handled = True
    End Select
End Sub

Upvotes: 7

tonycoupland
tonycoupland

Reputation: 4247

Return false from the onKeyDown handler function and it should prevent the 'a' being added.

Upvotes: 0

Related Questions