Home > Back-end >  Visual Studio 2017 VB: How can I make two buttons interact
Visual Studio 2017 VB: How can I make two buttons interact

Time:02-10

just started on VB, hope you can help me.

I'm doing a project about a game called TFT, where each item is made with two components. My project consists of 9 buttons, and by pressing two of them (could be the same one), I want to be able to get the specific item (as a msgbox).

Don't know if there's a better way to do it but I'm open to suggestions!

CodePudding user response:

Here's an example that changes the "Check" button to Green when Button3 is selected, followed by Button7 being selected, otherwise it changes the "Check" button to Red.

The buttons are arranged in a standard keypad grid:

Button1 Button2 Button3
Button4 Button5 Button6
Button7 Button8 Button9

Code:

Public Class Form1

    Private FirstButton As Button = Nothing
    Private SecondButton As Button = Nothing

    Private Buttons As List(Of Button)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Buttons = New List(Of Button)(
            {Button1, Button2, Button3,
            Button4, Button5, Button6,
            Button7, Button8, Button9})
        Buttons.ForEach(Sub(b) b.Text = "")
    End Sub

    Private Sub AllButtons_Click(sender As Object, e As EventArgs) _
        Handles Button1.Click, Button2.Click, Button3.Click,
        Button4.Click, Button5.Click, Button6.Click,
        Button7.Click, Button8.Click, Button9.Click

        Dim curButton As Button = DirectCast(sender, Button)
        If IsNothing(FirstButton) Then
            FirstButton = curButton
            FirstButton.Text = "1"
        ElseIf IsNothing(SecondButton) Then
            SecondButton = curButton
            If curButton Is FirstButton Then
                curButton.Text = "1, 2"
            Else
                SecondButton.Text = "2"
            End If
        Else
            FirstButton.Text = ""
            SecondButton.Text = ""
            FirstButton = curButton
            FirstButton.Text = "1"
            SecondButton = Nothing
        End If
    End Sub
    Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
        If FirstButton Is Button3 AndAlso SecondButton Is Button7 Then
            btnCheck.BackColor = Color.Green
        Else
            btnCheck.BackColor = Color.Red
        End If
    End Sub

End Class

Running example:

enter image description here

  • Related