共用方式為


HOW TO:在 Windows Form 上繪製文字

下列程式碼範例示範如何使用 GraphicsDrawString 方法,在表單上繪製文字。 此外,您也可以使用 TextRenderer 在表單上繪製文字。 如需詳細資訊,請參閱 HOW TO:使用 GDI 繪製文字

範例

    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;
    }

編譯程式碼

您不能在 Load 事件處理常式中呼叫 DrawString 方法。 如果表單被重新調整或被另一表單遮住,將不會重新繪製表單的內容。 若要自動重新繪製內容,您應該覆寫 OnPaint 方法。

穩固程式設計

以下條件可能會造成例外狀況:

  • 未安裝 Arial 字型

請參閱

工作

HOW TO:使用 GDI 繪製文字

參考

DrawString

DrawText

FormatFlags

StringFormatFlags

TextFormatFlags

OnPaint

其他資源

圖形程式設計入門