如何在c#winforms中添加上标幂运算符

我知道可以使用unicode值将square运算符添加到标签中。( 如何在.NET GUI标签中显示上标字符? )。 有没有办法为标签添加任何力量? 我的应用程序需要显示多项式函数,即x ^ 7 + x ^ 6等。

谢谢,迈克

您可以使用(伟大的) HtmlRenderer并构建自己的支持html的标签控件。

这是一个例子:

public class HtmlPoweredLabel : Control { protected override void OnPaint(PaintEventArgs e) { string html = string.Format(System.Globalization.CultureInfo.InvariantCulture, "
{2}
", 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 = x7 + x6"; 

结果:

在此处输入图像描述

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

您还可以使用本机支持的UTF字符串的强大function,并使用扩展方法将int(或甚至是uint)转换为字符串,如:

 public static class SomeClass { private static readonly string superscripts = @"⁰¹²³⁴⁵⁶⁷⁸⁹"; public static string ToSuperscriptNumber(this int @this) { var sb = new StringBuilder(); Stack digits = new Stack(); do { var digit = (byte)(@this % 10); digits.Push(digit); @this /= 10; } while (@this != 0); while (digits.Count > 0) { var digit = digits.Pop(); sb.Append(superscripts[digit]); } return sb.ToString(); } } 

然后以某种方式使用该扩展方法:

 public class Etc { private Label someWinFormsLabel; public void Foo(int n, int m) { // we want to write the equation x + x^N + x^M = 0 // where N and M are variables this.someWinFormsLabel.Text = string.Format( "x + x{0} + x{1} = 0", n.ToSuperscriptNumber(), m.ToSuperscriptNumber() ); } // the result of calling Foo(34, 2798) would be the label becoming: x + x³⁴+ x²⁷⁹⁸ = 0 } 

遵循这个想法,并进行一些额外的调整,(比如挂钩到文本框的TextChange和诸如此类的事件处理程序)你甚至可以允许用户编辑这样的“上标兼容”字符串(通过从其他按钮切换“上标模式”打开和关闭)在您的用户界面上)。

你可以将unicode转换为字符串,用于上标,下标和任何其他符号,并添加到字符串中。 例如:如果你想要10 ^ 6,你可以在C#或其他中编写如下代码。

电源6的unicode是U + 2076,电源7的unicode是U + 2077,所以你可以写x ^ 6 + x ^ 7

label1.Text =“X”+(char)0X2076 +“X”+(char)0x2077;