Chris
Chris

Reputation: 484

WinForms Anchor Control changes Location Origin?

I have been porting my C# / .NET 2.0 project over to Mono for use on other platforms, but this seems to have brought up a problem in the NATIVE WinForms implementation.

I have isolated the problem to the relationship between a Control's (specifically, a Button) Anchor property, and it's Location property's Y-component. When the AnchorStyle property is set to Top, the origin of the Location property is the ClientArea of the form (excluding the Title Bar). Changing the Anchor to Bottom, however changes the origin to the Top-Left corner of the entire Window (including the Title Bar).

Here's a small Form class which illustrates the difference:

public class RawCodeForm : Form
{
    public RawCodeForm()
    {
        Button b = new Button();
        b.Text = "Test";
        b.Location = new Point( 10, 10 );
        b.Size = new Size( 75, 23 );
        b.Anchor = AnchorStyles.Left | AnchorStyles.Top;
        //b.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;

        this.Controls.Add( b );
        this.Size = new Size( 100, 200 );
        this.Location = new Point( 100, 100 );
        this.Show();
    }
}

Try swapping the b.Anchor lines to see the change is position.

Is this a documented bug, or am I missing another property that needs to be set?


Edit: Thanks for pointing out that the Form starts as Size(300,300). I had assumed it was (0,0) until set.

Outside of the simple test form above, the problem now looks to be that the FormBorderStyle being changed later is causing the form to resize. My guess is that under Mono (or the host OS), the FormBorderStyle being changed resizes the ClientArea smaller, where-as the ClientSize area stays the same size in native WinForms.

Upvotes: 3

Views: 3546

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112632

This is because you change the size of the form after having added the button. Change it before

this.Size = new Size(100, 200);
this.Location = new Point(100, 100);

Button b = new Button();
b.Text = "Test";
b.Location = new Point(10, 10);
b.Size = new Size(75, 23);
//b.Anchor = AnchorStyles.Left | AnchorStyles.Top;
b.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;

this.Controls.Add(b);
this.Show();

The button just follows the change of the lower border when anchored to the bottom.

Upvotes: 4

Related Questions