如何:在 Windows 窗体上绘制文本

下面的代码示例演示如何使用 GraphicsDrawString 方法在窗体上绘制文本。 或者,可以使用 TextRenderer 在窗体上绘制文本。 有关更多信息,请参见 如何:用 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 字体。

请参见

任务

如何:用 GDI 绘制文本

参考

DrawString

DrawText

FormatFlags

StringFormatFlags

TextFormatFlags

OnPaint

其他资源

图形编程入门