是否可以在WinForms中旋转按钮控件?

时间:2011-02-26 21:54:17

标签: c# .net winforms button

是否可以在WinForms中以特定角度旋转按钮或任何控件?如果是这样,怎么样?

5 个答案:

答案 0 :(得分:7)

如果你真的想要(我不知道为什么会......)你可以尝试使用Button子类,也许是这样:

public partial class TurnButton : Button
{
    public TurnButton()
    {
        InitializeComponent();
    }

    int angle = 0;   // current rotation
    Point oMid;      // original center

    protected override void OnLayout(LayoutEventArgs levent)
    {
        base.OnLayout(levent);
        if (oMid == Point.Empty) oMid = new Point(Left + Width / 2, Top + Height / 2);
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
       int mx = this.Size.Width / 2;
       int my = this.Size.Height / 2;
       SizeF size = pe.Graphics.MeasureString(Text, Font);
       string t_ = Text;
       Text = "";

        base.OnPaint(pe);

        if (!this.DesignMode)
        {
            Text = t_; pe.Graphics.TranslateTransform(mx, my);
            pe.Graphics.RotateTransform(angle);
            pe.Graphics.TranslateTransform(-mx, -my);

            pe.Graphics.DrawString(Text, Font, SystemBrushes.ControlText,
                                  mx - (int)size.Width / 2, my - (int)size.Height / 2);
        }
    }



    protected override void OnClick(EventArgs e)
    {
        this.Size = new Size(Height, Width);
        this.Location = new Point(oMid.X - Width / 2, oMid.Y - Height / 2);
        angle = (angle + 90) % 360;
        Text = angle + "°";

        base.OnClick(e);
    }
}

(*我不知道为什么我写这个; - )

答案 1 :(得分:6)

您无法旋转控件。 WinForms使用的本机API控件根本不支持。

有人可能想知道为什么应该得到支持。您可能想要做什么,您需要旋转按钮控件?首先将它绘制在具有不同形状的不同位置更容易,而不是尝试旋转现有控件。 (请注意,如果符合您的需要,您还可以在运行时调整控件的大小并重新定位控件。调查SizeLocation属性。)

唯一的解决方法是将控件的图像绘制到位图,隐藏控件,并将位图绘制到您希望它出现的位置的表单上。当然,这不会导致用户可以交互的控件。他们将无法点击按钮的图像,因为它不是真正的按钮。如果您认为这是可以接受的,那么您应该首先使用图像,而不是按钮。

答案 2 :(得分:2)

这与此处提出的问题类似: Rotating a .NET panel in Windows Forms

该问题答案的快速摘要是,尽管可能会这样做,但它会非常非常复杂。

答案 3 :(得分:0)

在某些情况下可能的解决方法是:

使用tabControl,并调整其大小,以便只剩下按钮。将对齐设置为左/右,并使按钮旋转90/270度。

答案 4 :(得分:-2)

public class VerticalButton : Button
{
    public string VirticalText { get; set; }
    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);

        StringFormat stringFormat = new StringFormat();
        stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
        SolidBrush solidBrush = new SolidBrush(this.ForeColor);

        stringFormat.Alignment = StringAlignment.Center;
        stringFormat.LineAlignment = StringAlignment.Center;

        pe.Graphics.DrawString(VirticalText, this.Font, solidBrush,
            new Rectangle(0, 0, Width, Height), stringFormat);
    }
}