Custom Controls in vb .net

0

How to create custom controls in vb .net?

I would like to create and modify values of its properties. My purpose is to import them into other projects.

    
asked by anonymous 17.01.2018 / 18:48

1 answer

0

It's not easy. There are several possibilities, among them:

Using a UserControl // the easiest way

It is quite simple to create a set of controls, such as perhaps a list with some predefined buttons or perhaps a single control. You can always access the properties of your control if they are public and visible to the Designer.

Public Class MeuControle
     Inherits System.Windows.Forms.UserControl

     ' Propriedade interna             
     Private Dim _CorDeFundo As Color

     <DesignerSerializationVisibilityAttribute()>
     Public Property CorDeFundo As Color
           Get
                 Return _CorDeFundo
           End Get
           Set (value As Color)
                 _CorDeFundo = value
           End Set
     End Property
     ...
     ...

In the above code, the CorDeFundo property does not change anything in the code, it is only there to indicate that there is a property in the designer that changes the background color. To show this property in the designer, add the DesignerSerializationVisibilityAttribute over the method as above.

Learn about UserControl here .

Inheriting a Control directly // creating a control from zero

Here is a little more complicated, you will not use the designer to draw your control, will use everything based on the validations of the control, will have to implement a class that inherits the type System.Windows.Forms.Control and will have to emulate the events ( almost all) as MouseDown , OnPaint (what else will be used), Focused , etc.

One tip I give you is to look for several examples in CodeProject , there the staff develops quite a few controls.

Also take a look at this link .

Creating controls from controls

As @LINQ said, it is inheriting controls in its class. For example, you can change the color of the selection of a ListBox with this code:

Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
    e.DrawBackground()
    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        e.Graphics.FillRectangle(Brushes.LightSeaGreen, e.Bounds)
    End If
    Using b As New SolidBrush(e.ForeColor)
        e.Graphics.DrawString(ListBox1.GetItemText(ListBox1.Items(e.Index)), e.Font, b, e.Bounds)
    End Using
    e.DrawFocusRectangle()
End Sub

In short, it is not easy if you want to make a control from scratch, without using any other control as a basis. It's even easier to use UserControls.

    
17.01.2018 / 21:25