Vb . net Custom Controls

Asked

Viewed 209 times

0

How to create custom Vb . net controls?

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

  • 2

    Only create a class that extends/inherits control. For example: Public Class TextBoxPersonalizado Inherits TextBox

1 answer

1


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

Using a UserControl // the easiest way

It’s quite simple to create a set of controls, like maybe a little list with a few preset buttons or maybe a single controller. You will always be able to access the properties of your controller 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 code above, the property CorDeFundo 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 attribute DesignerSerializationVisibilityAttribute on top of the method as it is above.

Learn about the UserControl here.


Inheriting a Control directly // create a control from scratch

Here is a little more complicated, you will not use the designer to design your control, will use everything based on control validations, will have to implement a class that inherits the type System.Windows.Forms.Control and will have to emulate 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 enough controls.

Also take a look at this link (in English only).


Creating controls from controls

Like the @LINQ said, is inheriting controls in your class. For example, you can change the color of a selection 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’s not easy if you want to do a control from scratch without using any other control as a basis. It’s easier still using Usercontrols.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.