Como: Desenvolver um controle de formulários do Windows simples

Esta seção percorre as principais etapas para a criação de um controle personalizado do Windows Forms.O controle simples desenvolvido neste passo-a-passo permite o alinhamento dos seus Text propriedade a ser alterada. Não é elevar ou manipular eventos.

Criar um controle personalizado simples

  1. Definir uma classe que deriva de System.Windows.Forms.Control.

    Public Class FirstControl
       Inherits Control
    
    End Class
    
    public class FirstControl:Control{}
    
  2. Defina propriedades.(Não é necessário para definir propriedades, como um controle herdada muitas propriedades do Control classe, mas a maioria dos controles personalizados geralmente definir propriedades adicionais.) O fragmento de código a seguir define uma propriedade chamada TextAlignment que FirstControl usa para formatar a exibição da Text propriedade herdada de Control. Para obter mais informações sobre como definir propriedades, consulte Visão geral sobre propriedades.

    ' ContentAlignment is an enumeration defined in the System.Drawing
    ' namespace that specifies the alignment of content on a drawing 
    ' surface.
    Private alignmentValue As ContentAlignment = ContentAlignment.MiddleLeft
    
    <Category("Alignment"), Description("Specifies the alignment of text.")> _
    Public Property TextAlignment() As ContentAlignment
    
       Get
          Return alignmentValue
       End Get
       Set
          alignmentValue = value
    
          ' The Invalidate method invokes the OnPaint method described 
          ' in step 3.
          Invalidate()
       End Set
    End Property
    
    // ContentAlignment is an enumeration defined in the System.Drawing
    // namespace that specifies the alignment of content on a drawing 
    // surface.
    private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
    

    Quando você define uma propriedade que altera a exibição visual do controle, você deve chamar o Invalidate método para redesenhar o controle. Invalidate definido na classe base Control.

  3. Substituir o protegidoOnPaint método herdado da Control para fornecer a lógica de renderização para seu controle. Se você não substituirão OnPaint, o controle não poderá desenhar propriamente dito. No fragmento de código a seguir, a OnPaint método exibe a Text propriedade herdada de Control com o alinhamento especificado pela alignmentValue campo.

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
    
       MyBase.OnPaint(e)
       Dim style As New StringFormat()
       style.Alignment = StringAlignment.Near
       Select Case alignmentValue
          Case ContentAlignment.MiddleLeft
             style.Alignment = StringAlignment.Near
          Case ContentAlignment.MiddleRight
             style.Alignment = StringAlignment.Far
          Case ContentAlignment.MiddleCenter
             style.Alignment = StringAlignment.Center
       End Select
    
       ' Call the DrawString method of the System.Drawing class to write   
       ' text. Text and ClientRectangle are properties inherited from
       ' Control.
       e.Graphics.DrawString( _
           me.Text, _
           me.Font, _
           New SolidBrush(ForeColor), _
           RectangleF.op_Implicit(ClientRectangle), _
           style)
    
    End Sub
    
    protected override void OnPaint(PaintEventArgs e) 
    {   
        base.OnPaint(e);
        StringFormat style = new StringFormat();
        style.Alignment = StringAlignment.Near;
        switch (alignmentValue) 
        {
            case ContentAlignment.MiddleLeft:
                style.Alignment = StringAlignment.Near;
                break;
            case ContentAlignment.MiddleRight:
                style.Alignment = StringAlignment.Far;
                break;
            case ContentAlignment.MiddleCenter:
                style.Alignment = StringAlignment.Center;
                break;
        }
    
        // Call the DrawString method of the System.Drawing class to write   
        // text. Text and ClientRectangle are properties inherited from
        // Control.
        e.Graphics.DrawString(
            Text, 
            Font, 
            new SolidBrush(ForeColor), 
            ClientRectangle, style);
    
    } 
    
  4. Fornece atributos para seu controle.Atributos permitem que um designer visual exibir seu controle e suas propriedades e eventos adequadamente em time de design.O fragmento de código a seguir aplica atributos à TextAlignment propriedade. Em um designer sistema autônomo o Visual Studio, a Category atributo (mostrado no fragmento de código) faz com que a propriedade a ser exibido em uma categoria lógica. The Description atributo faz com que uma seqüência de caracteres descritiva a ser exibido na parte inferior da Propriedades janela quando o TextAlignment propriedade é selecionada. Para obter mais informações sobre atributos, consulte Atributos de tempo de design para componentes.

    <Category("Alignment"), Description("Specifies the alignment of text.")> _
    Public Property TextAlignment() As ContentAlignment
    
    [
    Category("Alignment"),
    Description("Specifies the alignment of text.")
    ]
    
  5. (opcional) Fornecer recursos para seu controle.Você pode fornecer um recurso, sistema autônomo um bitmap para seu controle usando uma opção do compilador (/res para translation from VPE for Csharp) aos recursos de pacote com seu controle. Em time de execução, o recurso pode ser recuperado usando os métodos do ResourceManager classe. Para obter mais informações sobre como criar e usar recursos, consulte o Recursos em aplicativos.

  6. compilar e implante seu controle.Para compilar e implantar FirstControl, executar as seguintes etapas:

    1. salvar o código no exemplo a seguir para um arquivo de fonte (sistema autônomo FirstControl.cs ou FirstControl.vb).

    2. compilar o código-fonte em um assembly e salvar-o no diretório do aplicativo.Para fazer isso, executar o seguinte comando no diretório que contém o arquivo de fonte.

      vbc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.vb
      
      csc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.cs
      

      The /t:library opção do compilador informa ao compilador que o assembly que você está criando é uma biblioteca (e não um executável). The /out opção especifica o caminho e nome do assembly. The/r opção fornece o nome dos conjuntos de módulos (assemblies) referenciados pelo seu código. Neste exemplo, você cria um conjunto particular que somente os aplicativos podem usar.Portanto, você precisará salvá-lo no diretório do aplicativo.Para obter mais informações sobre empacotamento e implantação de um controle para distribuição, consulte Implantando aplicativos .NET Framework.

O exemplo a seguir mostra o código para FirstControl. O controle está entre no namespace CustomWinControls. A namespace fornece um agrupamento lógico de tipos relacionados.Você pode criar seu controle em um novo ou existente namespace.Em translation from VPE for Csharp, o using declaração (no Visual Basic Imports) permite tipos seja acessado por um espaço para nome sem usar o nome totalmente qualificado do tipo. No exemplo a seguir, a using declaração permite que o código acessar a classe Control de System.Windows.Forms sistema autônomo simplesmente Control em vez de usar o nome totalmente qualificado System.Windows.Forms.Control.

Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms


Public Class FirstControl
   Inherits Control

   Public Sub New()
   End Sub 


   ' ContentAlignment is an enumeration defined in the System.Drawing
   ' namespace that specifies the alignment of content on a drawing 
   ' surface.
   Private alignmentValue As ContentAlignment = ContentAlignment.MiddleLeft

   <Category("Alignment"), Description("Specifies the alignment of text.")> _
   Public Property TextAlignment() As ContentAlignment

      Get
         Return alignmentValue
      End Get
      Set
         alignmentValue = value

         ' The Invalidate method invokes the OnPaint method described 
         ' in step 3.
         Invalidate()
      End Set
   End Property


   Protected Overrides Sub OnPaint(e As PaintEventArgs)

      MyBase.OnPaint(e)
      Dim style As New StringFormat()
      style.Alignment = StringAlignment.Near
      Select Case alignmentValue
         Case ContentAlignment.MiddleLeft
            style.Alignment = StringAlignment.Near
         Case ContentAlignment.MiddleRight
            style.Alignment = StringAlignment.Far
         Case ContentAlignment.MiddleCenter
            style.Alignment = StringAlignment.Center
      End Select

      ' Call the DrawString method of the System.Drawing class to write   
      ' text. Text and ClientRectangle are properties inherited from
      ' Control.
      e.Graphics.DrawString( _
          me.Text, _
          me.Font, _
          New SolidBrush(ForeColor), _
          RectangleF.op_Implicit(ClientRectangle), _
          style)

   End Sub

End Class
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{
    public class FirstControl : Control
    {

        public FirstControl()
        {

        }

        // ContentAlignment is an enumeration defined in the System.Drawing
        // namespace that specifies the alignment of content on a drawing 
        // surface.
        private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;

        [
        Category("Alignment"),
        Description("Specifies the alignment of text.")
        ]
        public ContentAlignment TextAlignment 
        {

            get 
            {
                return alignmentValue;
            }
            set 
            {
                alignmentValue = value;

                // The Invalidate method invokes the OnPaint method described 
                // in step 3.
                Invalidate(); 
            }
        }


        protected override void OnPaint(PaintEventArgs e) 
        {   
            base.OnPaint(e);
            StringFormat style = new StringFormat();
            style.Alignment = StringAlignment.Near;
            switch (alignmentValue) 
            {
                case ContentAlignment.MiddleLeft:
                    style.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    style.Alignment = StringAlignment.Far;
                    break;
                case ContentAlignment.MiddleCenter:
                    style.Alignment = StringAlignment.Center;
                    break;
            }

            // Call the DrawString method of the System.Drawing class to write   
            // text. Text and ClientRectangle are properties inherited from
            // Control.
            e.Graphics.DrawString(
                Text, 
                Font, 
                new SolidBrush(ForeColor), 
                ClientRectangle, style);

        } 
    }
}

Usando o controle personalizado em um formulário

O exemplo a seguir mostra um formulário simples que usa FirstControl. Ele cria três ocorrências de FirstControl, cada um com um valor diferente para o TextAlignment propriedade.

Para compilar e executar esse exemplo

  1. salvar o código no exemplo a seguir para um arquivo de fonte (SimpleForm.cs ou SimpleForms.vb).

  2. compilar o código-fonte em um assembly executável, executando o seguinte comando no diretório que contém o arquivo de origem.

    vbc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.vb
    
    csc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.cs
    

    CustomWinControls.dll é o assembly que contém a classe FirstControl. Neste módulo (assembly) deve estar no mesmo diretório que o arquivo de fonte para o formulário que acessa (SimpleForm.cs ou SimpleForms.vb).

  3. executar SimpleForm.exe usando o comando a seguir.

    SimpleForm
    
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms




Public Class SimpleForm
   Inherits System.Windows.Forms.Form

   Private firstControl1 As FirstControl

   Private components As System.ComponentModel.Container = Nothing


   Public Sub New()
      InitializeComponent()
   End Sub 





   Private Sub InitializeComponent()
      Me.firstControl1 = New FirstControl()
      Me.SuspendLayout()

      ' 
      ' firstControl1
      ' 
      Me.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark
      Me.firstControl1.Location = New System.Drawing.Point(96, 104)
      Me.firstControl1.Name = "firstControl1"
      Me.firstControl1.Size = New System.Drawing.Size(75, 16)
      Me.firstControl1.TabIndex = 0
      Me.firstControl1.Text = "Hello World"
      Me.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter

      ' 
      ' SimpleForm
      ' 
      Me.ClientSize = New System.Drawing.Size(292, 266)
      Me.Controls.Add(firstControl1)
      Me.Name = "SimpleForm"
      Me.Text = "SimpleForm"
      Me.ResumeLayout(False)
   End Sub 


   <STAThread()>  _
   Shared Sub Main()
      Application.Run(New SimpleForm())
   End Sub 
End Class 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{

    public class SimpleForm : System.Windows.Forms.Form
    {
        private FirstControl firstControl1;

        private System.ComponentModel.Container components = null;

        public SimpleForm()
        {
            InitializeComponent();
        }

        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        private void InitializeComponent()
        {
            this.firstControl1 = new FirstControl();
            this.SuspendLayout();

            // 
            // firstControl1
            // 
            this.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark;
            this.firstControl1.Location = new System.Drawing.Point(96, 104);
            this.firstControl1.Name = "firstControl1";
            this.firstControl1.Size = new System.Drawing.Size(75, 16);
            this.firstControl1.TabIndex = 0;
            this.firstControl1.Text = "Hello World";
            this.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter;

            // 
            // SimpleForm
            // 
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.firstControl1);
            this.Name = "SimpleForm";
            this.Text = "SimpleForm";
            this.ResumeLayout(false);

        }

        [STAThread]
        static void Main() 
        {
            Application.Run(new SimpleForm());
        }


    }
}

Consulte também

Conceitos

Eventos em controles Windows Forms

Outros recursos

Propriedades em controles Windows Forms