hi friends,
I have designed a simple calculator using vb.net I want to execute click event of button which labeled as "1", when I press key "1" on keyboard. please help me.

Recommended Answers

All 3 Replies

Normal buttons require ALT-key to be pressed. If you don't mind this, name the buttons

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' 
    Button1.Text = "&1"
    Button2.Text = "&2"
    
  End Sub

and trap "number"-buttons

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
    Select Case CType(sender, Button).Text
      Case "&1"
         ' Number 1 pressed
      Case "&2"
         ' Number 2 pressed
    End Select

  End Sub

If you do not want ALT-key to be used, you have to trap KeyUp or similar event and use some other control instead of Button control.

I assume you have your click event sub proceedure running, to add another event for a button say "button1" you have to make sure you have enable its 'tabstop' property and then you can add another event sub proceedure.

However for your calculator, when the tabstop gets to the 'btn1' button all the user has to do is to press the "enter key".

This is in simple context, however you may have to implement threading for complex scenario where you need responses. (My opinion)

I am leaving you with some code snippet for your review, it may help.

Private Sub btn1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles btn1.KeyPress
        
Dim keyasc As Short 

        If keyasc >= System.Windows.Forms.Keys.D1 And keyasc <= System.Windows.Forms.Keys.D9 Then
            txtDisplay.Text = Val(btn1.Text)
            Exit Sub
        Else
            MessageBox.Show("Error key pressed")

        End If

    End Sub

thanks Teme64
thanks for sharing your code with us i think it will defiantly useful for someone.good job..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.