It's a quite old question, but maybe i'm able to answer it.
After reading all your comments, i think i can summarize your problem to this:
- You have a form at a specific size and add some controls at runtime at a specific location with anchor set to
Top | Right
.
- If you just display the form and let the controls appear everything works fine
- If you maximize your form (or change the size of it) your controls won't be appear anymore at the correct location you want.
To get rid of this problem you can try some different approaches:
- Use a FlowLayoutPanel, take care for the FlowDirection and maybe just create all your needed controls beforehand and just toggle the visible state.
- Use correct values for the location of your newly created controls.
The second point is the error you have (i think). You found someway to calculate the location of your control if your form has it's original size. To get the correct position if the size of the form has changed (e.g. maximized) you have to consider several factors.
- The delta values from your default size to your current size.
- The Anchor(s) you wish to set on your control.
In your case you'd like to put a control which is anchored Top | Right
, but the location is set by Top | Left
. In that case you have to calculate the difference between the control.location.x and the form.width in it's default size. Then you take this difference and subtract it from the form current width. Now you can place your control at this position (cause Top never changes through a resizing). If you have a Anchor at Bottom | Right
you have to calculate the same with control.location.y and form.height.
The behaviour and calculation if no anchor, for Top | Bottom
or Left | Right
are set is left as an exercise to the reader. ;-)
Last but not least there is also another hacky way to get your control at the right position:
- If you like to place a new control somewhere change the
Form.Visible
to false
- Save the form state, size and location
- Change them to your default values
- Add the controls you want
- Restore the formerly saved values
- Make the form visible again.