Comment : dessiner du texte dans un Windows Form

L'exemple de code suivant montre comment utiliser la méthode DrawString de Graphics pour dessiner du texte sur un formulaire. Vous pouvez également utiliser TextRenderer pour dessiner le texte sur un formulaire. Pour plus d'informations, consultez Comment : écrire du texte avec GDI.

Exemple

    Public Sub DrawString()
        Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
        Dim drawString As String = "Sample Text"
        Dim drawFont As New System.Drawing.Font("Arial", 16)
        Dim drawBrush As New _
           System.Drawing.SolidBrush(System.Drawing.Color.Black)
        Dim x As Single = 150.0
        Dim y As Single = 50.0
        Dim drawFormat As New System.Drawing.StringFormat
        formGraphics.DrawString(drawString, drawFont, drawBrush, _
            x, y, drawFormat)
        drawFont.Dispose()
        drawBrush.Dispose()
        formGraphics.Dispose()
    End Sub

    public void DrawString()
    {
        System.Drawing.Graphics formGraphics = this.CreateGraphics();
        string drawString = "Sample Text";
        System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16);
        System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
        float x = 150.0F;
        float y = 50.0F;
        System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
        formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
        drawFont.Dispose();
        drawBrush.Dispose();
        formGraphics.Dispose();
    }

public:
    void DrawString()
    {
        System::Drawing::Graphics^ formGraphics = this->CreateGraphics();
        String^ drawString = "Sample Text";
        System::Drawing::Font^ drawFont =
            gcnew System::Drawing::Font("Arial", 16);
        System::Drawing::SolidBrush^ drawBrush = gcnew
            System::Drawing::SolidBrush(System::Drawing::Color::Black);
        float x = 150.0F;
        float y = 50.0F;
        System::Drawing::StringFormat^ drawFormat =
            gcnew System::Drawing::StringFormat();
        formGraphics->DrawString(drawString, drawFont, drawBrush, x,
            y, drawFormat);
        delete drawFont;
        delete drawBrush;
        delete formGraphics;
    }

Compilation du code

Vous ne pouvez pas appeler la méthode DrawString dans le gestionnaire d'événements Load. Le contenu dessiné ne sera pas redessiné si le formulaire est redimensionné ou s'il est occulté par un autre formulaire. Pour que votre contenu soit automatiquement repeint, vous devez substituer la méthode OnPaint.

Programmation fiable

Les conditions ci-dessous peuvent générer une exception.

  • La police Arial n'est pas installée.

Voir aussi

Tâches

Comment : écrire du texte avec GDI

Référence

DrawString

DrawText

FormatFlags

StringFormatFlags

TextFormatFlags

OnPaint

Autres ressources

Mise en route de la programmation graphique