Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.Parent and StartPosition.CenterParent

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.

like image 870
Odys Avatar asked Jun 08 '12 08:06

Odys


People also ask

How do I Center a form within the parent form?

Centers the position of the form within the bounds of the parent form. Do not call the CenterToParent method directly from your code. Instead, set the StartPosition property to CenterParent. If the form or dialog is top-level, then CenterToParent centers the form with respect to the screen or desktop.

How to access parent form from child form?

Anyway, if you want to have access to the parent form you can set it to Owner property of the child form: Then in the child form you can access the parent form using the Owner property. When a form is owned by another form, it is minimized and closed with the owner form.

Is there a way to set the child-parent relationship for forms?

Child-parent relationship is made defunct for forms. There is no special solution for this "problem". You simply need to use the property Location and Size for both form and set location of one form the way it is placed in the middle of another one.

What is centerparent in WinForms?

In this context, CenterParent really means CenterOwner. Not a Windows capability, it is implemented in Winforms, done by the base Form.OnLoad () method.


1 Answers

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);
like image 166
DmitryG Avatar answered Sep 18 '22 17:09

DmitryG