Dhika Dhika -4 years ago 86
Vb.net Question

Custom Radiobutton Control (Winforms)

I want to make a custom radiobutton control for my own project. I expect this control to be have custom indicator on it (as regular radiobutton indicator is a dot. It's boring :D) and the indicator is a string, because I'll use a glyph font.

I've already tried to inherit the control and use custom Paint method but what I get is like this.
My code is this

Public Class Component1
Inherits RadioButton
Private Icons As String = "ABC XGTDJS"
Private Captions As String

Dim x As New Font("Segoe UI", 10)
Dim y As New SolidBrush(Color.Black)
Dim z As New Point(0, 0)

Private Sub Component1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.DrawString(Icons, x, y, z)

End Sub
End Class


Protected Overrides Sub OnPaint(e As PaintEventArgs)
e.Graphics.DrawString(Icons, x, y, z)
SetStyle(ControlStyles.UserPaint, True)

End Sub

also have the same effect.

So I'm thinking to make this control from scratch. My questions are :

  • Is it possible for the RadioButton control to be completely user-drawn?

  • I've already made a custom Checkbox control (which fulfills the expectation above). For example, if I have 3 checkboxes, I could check them all. But if I have 3 radiobuttons, I couldn't check them all (of course). How could I achieve this effect? I know I could manually program 'if checkbox 1 checked, checkbox 2 and 3 unchecked' but that is not feasible. It would be better done on the usercontrol level so the main form that use it would be way more tidy and nice :D

Sorry if my English is bad :D

Answer Source

No need to make it from scratch, there's just something you've been missing:

The Paint event is raised by the OnPaint method, so your first example will always draw the regular radio button. This you can't do anything about.

However in your second example you explicitly tell it to draw the original radio button:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
End Sub

By calling MyBase.OnPaint() you essentially call the RadioButton.OnPaint() method (since your control is inherited from it, its base is RadioButton), which will result in the original radio button being drawn.

Remove that call and you should be good to go. Also, do not call SetStyle() every time you paint, you only need to call it in the constructor (however right now you don't need to call it at all, so just remove it).

Having that said, here's what your OnPaint method should look like:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    e.Graphics.DrawString(Icons, x, y, z)
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download