genespos genespos - 2 months ago 20 Question

Prevent raising Click event on RadioButton while moving from one to another

I have a Form with a Panel containig 5 RadioButton

I've only handled the Click event of all RadioButtons.

When I use arrow keys to move from a RadioButton to another, the Click event is raised at each move.

Is it possible to only Select the RadioButton and Click it using SpaceBar?


I would you use the Form.KeyDown event of the parent form and do something like this:

Private Sub Form1_KeyPress(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    REM Check if space is the button pressed
    If e.KeyCode = Keys.Space Then
        REM See if a Radio Button has focus to know which was selected
        If RadioButton1.ContainsFocus Then
        ElseIf RadioButton2.ContainsFocus Then
        End If
    End If
End Sub

''' <summary>
''' Method which executes the code you want run when a radio button is selected
''' </summary>
''' <param name="rdButtona"></param>
Private Sub RunMyCode(ByRef rdButtona As RadioButton)
    REM Check which radio button was selected and execute the apprpriate code
    If rdButtona.Equals(RadioButton1) Then
        MsgBox("Radio Button 1")
    ElseIf rdButtona.Equals(RadioButton2) Then
        MsgBox("Radio Button 2")
    End If
End Sub

To prevent the RadioButton from being checked, handle the RadioButton.Click event and uncheck the RadioButton using radioButton1.checked = false. If you handle the RadioButton.CheckChanged event, radioButton1.checked = false will raise another CheckChanged event which we don't need. I would also do something there to show which radio button has been selected. In My example I change the text color but you can do whatever you want.

   Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
    RadioButton2.Checked = False
    RadioButton2.ForeColor = Color.DarkRed
End Sub

Private Sub RadioButton3_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton3.CheckedChanged
    RadioButton3.Checked = False
    RadioButton3.ForeColor = Color.DarkRed
End Sub

Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
    RadioButton1.Checked = False
    RadioButton1.ForeColor = Color.DarkRed
End Sub

Private Sub ResetColors()
    RadioButton2.ForeColor = Color.Black
    RadioButton1.ForeColor = Color.Black
    RadioButton3.ForeColor = Color.Black
End Sub

Of course the code could be simplified, but this is the general idea.