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.
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.
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.
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.
In this context, CenterParent really means CenterOwner. Not a Windows capability, it is implemented in Winforms, done by the base Form.OnLoad () method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With