且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#WinForms中添加上标幂运算符

更新时间:2023-12-05 17:50:22

您可以使用(great) HtmlRenderer

You can use the (great) HtmlRenderer and build you own label control supporting html.

以下是一个示例:

public class HtmlPoweredLabel : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        string html = string.Format(System.Globalization.CultureInfo.InvariantCulture,
        "<div style=\"font-family:{0}; font-size:{1}pt;\">{2}</div>",
        this.Font.FontFamily.Name,
        this.Font.SizeInPoints,
        this.Text);

        var topLeftCorner = new System.Drawing.PointF(0, 0);
        var size = this.Size;

        HtmlRenderer.HtmlRender.Render(e.Graphics, html, topLeftCorner, size);

        base.OnPaint(e);
    }
}

用法示例:

// add an HtmlPoweredLabel to you form using designer or programmatically,
// then set the text in this way:
this.htmlPoweredLabel.Text = "y = x<sup>7</sup> + x<sup>6</sup>";

结果:

请注意,此代码将html包装为div部分,将字体系列和大小设置为控件使用的字体和大小。因此,您可以通过更改标签的 Font 属性来更改大小和字体。

Note that this code wraps your html into a div section that sets the font family and size to the one used by the control. So you can change the size and font by changing the Font property of the label.