0

Is there a way in C# WinForms (or Win32 API) to offset the origin {0,0} coordinate for child controls of a form without adding a control as a parent and without extending the window border?

This is what I mean:

Change origin WinForms

Does the Win32 API have something like a SetChildOffset() function? I want the window border to stay the same.

MathuSum Mut
  • 2,765
  • 3
  • 27
  • 59
  • Do you mean you want to change the [ClientRectangle](https://stackoverflow.com/questions/28277039/how-to-set-the-client-area-clientrectangle-in-a-borderless-form)? – TaW Sep 09 '18 at 13:30
  • Why not just add the controls where you want them? Is there any cost also to using a panel? Please explain the purpose being your problem so that we can help you come up with a reasonable solution. – siride Sep 09 '18 at 16:16

1 Answers1

3

There is no API to do this. Instead use this:

private void SetChildOffset(int offset) {
    //get all immediate children of form
    var children = this.Controls.OfType<Control>();

    foreach( Control child in children ) {

        child.Location = new Point( child.Location.X + offset, child.Location.Y + offset );

    }

}
  • I might also see the [Rectangle.Offset()](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.offset) method. The `SetChildOffset()` method could accept a `Point` as parameter (the `Button.Location`, in this case), define a `Rectangle bounds == ChildControl.Bounds` then call `bounds.Offset([Point])` to translate the Bounds position. Cannot be directly called on a `Control.Bounds` property. – Jimi Sep 11 '18 at 00:09
  • Not my method :) It's just the pre-defined one. The meaning of the comment is that you can't offset a location with an single `int` value. You need both `X` and `Y` positions. The `Offset()` method works like this: `Point Offset = [ReferenceControl].Location; Rectangle bounds = [Control].Bounds; bounds.Offset(Offset); [Control].Bounds = bounds;`. I won't post another answer. There's no need for it. – Jimi Sep 11 '18 at 01:18
  • @Jimi Aaa! Ye, i got it. Of cource it should be a `Point` not an `int`. I didn't even think of it! Nice catch – γηράσκω δ' αεί πολλά διδασκόμε Sep 11 '18 at 01:54
  • Thanks a very useful easy solution. I think I also read people recommending panels, but this is the easiest solution for sure! – Lee Oct 03 '22 at 09:49