davidib17 davidib17 - 1 month ago 8
Vb.net Question

How to make a right click do something different than a left click in Visual Basic?

This is like my first time programming so excuse the rookie question. I'm working on a project for school, in which if someone left-clicks on a picture, it adds 1 to a value in a textbox. I've already gotten that done. However, I'd like to make it so that if someone right-clicks the picturebox, it subtracts 1 from the value in the textbox. I have no clue how to do this, google isn't helping for some reason.

Is there a pretty straightforward way of doing this?

Answer

There is no "right click" event, but inside all the mouse click events (click, double click, down, up) you can check the event args for which mouse button was pressed, and then use an if block to determine which set of logic gets executed. Here's an example:

Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
    If e.Button = Windows.Forms.MouseButtons.Left Then
        'logic to add 1 to textbox value
    ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
        'logic to subtract 1 from textbox value
    End If
End Sub

Edited for your specific case of a picturebox:

Private Sub PB_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick
    If e.Button = Windows.Forms.MouseButtons.Left Then
        'logic to add 1 to textbox value
    ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
        'logic to subtract 1 from textbox value
    End If
End Sub

*Note that this sub has MouseEventArgs in its arguments, and handles PictureBox1's MouseClick event...Those are important, as pointed out by Pro Grammer

Comments