Is it possible to rotate a button control in WinForms?

23,216

Solution 1

You can't rotate controls. That's simply not supported by the native API controls that WinForms uses.

And one might wonder why it even should be supported. What could you possibly be trying to do that you'd need to rotate a button control? It would be much easier to draw it in a different place with a different shape in the first place, rather than trying to rotate an existing control. (Do note that you can also resize and reposition a control at run-time, if that would fit your needs. Investigate the Size and Location properties.)

The only workaround is to draw the control's image to a bitmap, hide the control, and draw the bitmap onto the form in the location you want it to appear. Of course, that won't result in a control that the user can interact with. They won't be able to click an image of a button, because it's not a real button. If that's acceptable to you, you should probably be using an image in the first place, rather than a button.

Solution 2

If you really want to (I have no idea why one would..*) you could try to use a Button subclass, maybe like that:

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);
    }
}

(* I have no idea why I wrote that, either ;-)

Solution 3

This is similar to the question asked here: Rotating a .NET panel in Windows Forms

The quick summary of answers from that question is that while it may be possible to do it, it would be very, very complicated.

Share:
23,216
SajjadZare
Author by

SajjadZare

Updated on July 19, 2022

Comments

  • SajjadZare
    SajjadZare almost 2 years

    Is it possible to rotate a button or any control at a particular angle in WinForms? If so, how?