Search code examples
vb.netkeyboardarrow-keys

Disable selection of buttons by enterkey in vb


I have designed a calculator. Basically I have a label, and some buttons which includes btn0........ btn9, etc, btnequals. Now When i click on btn0...btn1 it enters the number into the label.But I want to use keyboard instead of mouse.When i set the forms key preview property to true and use the code below everything works well but when you use the arrow keys it moves the selected button and then when i press enter it press the button which is selected.

Criteria's of this problems:

1)It is not possible to use a text-box instead of label.

One of these solutions can help me...

1)Disabling the enter key completely.It should be as if a dead key on the keyboard.

2)Disabling the program to select the buttons even when the arrow key is moved.

3)Programming in such a way that It should click the equals button only when i press the enter key.

Please help me to get rid of this problem. And thanks in advance.

The code i have used is:

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

    If e.KeyChar = "0" Then
        Btn0.PerformClick()
    ElseIf e.KeyChar = "1" Then
        Btn1.PerformClick()
    ElseIf e.KeyChar = "2" Then
        Btn2.PerformClick()
    ElseIf e.KeyChar = "3" Then
        Btn3.PerformClick()
    ElseIf e.KeyChar = "4" Then
        Btn4.PerformClick()
    ElseIf e.KeyChar = "5" Then
        Btn5.PerformClick()
    ElseIf e.KeyChar = "6" Then
        Btn6.PerformClick()
    ElseIf e.KeyChar = "7" Then
        Btn7.PerformClick()
    ElseIf e.KeyChar = "8" Then
        Btn8.PerformClick()
    ElseIf e.KeyChar = "9" Then
        Btn9.PerformClick()
    Else
        'Donothing Just Ignore
    End If
End Sub

Solution

  • I recently ran into this problem, and the solution I came up with was quick and simple. Just move focus to the label after every time a button is pressed! For instance, do this:

    Private Sub Btn0_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'Do stuff
        Label1.Focus()
    End Sub
    

    This focuses the label which means that the button will be de-focused which means that it will not be clicked when you press enter. Good luck!