Compartilhar via


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 simple desenvolvido nesta explicação permite o alinhamento de sua Text propriedade a ser alterada. Ele não elevar ou manipular eventos.

Para 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, porque muitas propriedades de um controle é herdada da 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 do 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 protegido OnPaint método herdado de Control para fornecer a lógica de renderização para o seu controle. Se você não substituir OnPaint, o controle não consiga desenhar a mesmo. No fragmento de código a seguir, o OnPaint método exibe o Text propriedade herdada de Control com o alinhamento especificado pelo 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 o seu controle. Atributos permitem que um designer visual exibir adequadamente seu controle e suas propriedades e eventos em tempo de design. O fragmento de código a seguir se aplica a atributos para o TextAlignment propriedade. Em um designer como, por exemplo, Visual Studio, o Category (mostrado no fragmento de código) do atributo faz com que a propriedade a ser exibida em uma categoria lógica. O Description atributo faz com que uma seqüência descritiva ser exibido na parte inferior do Propriedades janela quando o TextAlignment propriedade for 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) Fornece recursos para o seu controle. Você pode fornecer um recurso, como, por exemplo, um bitmap para o seu controle usando uma opção de compilador (/res para C#) para os recursos do pacote com o seu controle. Em tempo de execução, o recurso pode ser recuperado usando os métodos de ResourceManager classe. Para obter mais informações sobre a criação e uso de recursos, consulte o Recursos em aplicativos.

  6. Compilar e implantar o seu controle. Para compilar e implantar FirstControl, executar as etapas a seguir:

    1. Salve o código no exemplo a seguir em um arquivo de origem (como, por exemplo, FirstControl.cs ou FirstControl.vb).

    2. Compilar o código-fonte em um assembly e salve-o no diretório do aplicativo. Para fazer isso, execute o seguinte comando a partir do diretório que contém o arquivo de origem.

      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
      

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

O exemplo a seguir mostra o código para FirstControl. O controle é encerrado no namespace CustomWinControls. Um espaço para nome fornece um agrupamento lógico de tipos relacionados. Você pode criar seu controle em um namespace de novo ou existente. Em C# a using declaração (em Visual Basic, Imports) permite que os tipos de ser acessado a partir de um espaço para nome sem usar o nome totalmente qualificado do tipo. No exemplo a seguir, o using declaração permite que o código para acessar a classe Control de System.Windows.Forms como 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 instâncias do FirstControl, cada um com um valor diferente para o TextAlignment propriedade.

Para compilar e executar esse exemplo.

  1. Salve o código no exemplo a seguir em um arquivo de origem (SimpleForm.cs ou SimpleForms.vb).

  2. Compile o código-fonte em um assembly executável executando o seguinte comando do 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. Este assembly deve estar no mesmo diretório que o arquivo de origem para o formulário que acessa (SimpleForm.cs ou SimpleForms.vb).

  3. Execute 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 de controles do Windows Forms