在按钮内设置文本样式

时间:2013-05-30 14:29:45

标签: c# winforms button

我想在我的按钮中有一个多行文本字符串,如下所示:

myButton.Text = "abc" + Environment.NewLine + "123";

是否可以单独设置每一行的样式?例如我希望第一行是粗体,第二行是斜体?

如果无法做到这一点,有人可以推荐另一种方法来实现这一目标吗?

谢谢

1 个答案:

答案 0 :(得分:3)

要做到这一点可能需要做很多工作,但这是一个开始。

这将是继承的类:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class MyButton : Button
    {
        private Boolean _pressed = false;

        protected override void OnPaint(PaintEventArgs pevent)
        {
            if (_pressed)
                ControlPaint.DrawButton(pevent.Graphics, pevent.ClipRectangle, ButtonState.Pushed);
            else
                ControlPaint.DrawButton(pevent.Graphics, pevent.ClipRectangle, ButtonState.Normal);

            pevent.Graphics.DrawString("Line 1", new System.Drawing.Font("Arial", 8.5f, System.Drawing.FontStyle.Regular), System.Drawing.Brushes.Black, new System.Drawing.PointF(2.0f, 2.0f));
            pevent.Graphics.DrawString("Line 2", new System.Drawing.Font("Tahoma", 14.0f, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Red, new System.Drawing.PointF(2.0f, 17.0f));
        }

        protected override void OnMouseUp(MouseEventArgs mevent)
        {
            _pressed = false;
            base.OnMouseUp(mevent);
        }

        protected override void OnMouseDown(MouseEventArgs mevent)
        {
            _pressed = true;
            base.OnMouseDown(mevent);
        }
    }
}

您必须以编程方式向表单添加MyButton对象,或添加普通按钮并转到Form1.Designer.cs并将其类型从Button更改为MyButton

请注意,我不是使用Text1 + Environment.NewLine + Text2,而是通过精确定位来绘制。这使您可以准确计算出它需要的位置。

您可以利用Graphics.MeasureString进一步帮助自己。这可以帮助您确定您绘制的字符串的确切大小,以了解它消耗的空间。

您还需要确保按钮始终足够大,以便正确显示您要显示的文本。也可以在覆盖中完成,或者在设计时将其设置为设置大小并使文本适合它。取其。

相关问题