Form.Parent and StartPosition.CenterParent

.net-3.5, c#, winforms

Solution

The information about the owner is passed to the created dialog via the API call (you can see that in Reflector within the ShowDialog(IWin32Window owner) method):

UnsafeNativeMethods.SetWindowLong(new HandleRef(this, base.Handle), -8, new HandleRef(owner, handle));

When there is no owner specified in ShowDialog call the `owner` variable is calcualated via the GetActiveWindow API call:

IntPtr activeWindow = UnsafeNativeMethods.GetActiveWindow();
IntPtr handle = (owner == null) ? activeWindow : Control.GetSafeHandle(owner);

To get access to the Owner f dialog form you can use the GetWindowLong API call:

IntPtr ownerHandle = NativeMethods.GetWindowLong(nonModalForm.Handle, -8);

Problem

I need to show a form exactly in front of another form, this lead me to the following question. How come a form can have a start position as `CenterParent` while having the field `this.Parent` equals to null? It must know the parent in order to position itself correctly, which it does, but the `Parent` field is not set. This is odd. Am I missing something? ``` Form2 f = new Form2(); f.ShowDialog(); ``` Thats all I do on the child form. The parent is set to default windows position. No matter where I move the parent form, the child is shown in the center of the parent.

Original source

Related problems