3

I have a Form that needs to sit on top of two other forms. It should also minimize with one of the two forms it sits above. I found that this works as described when I do

form.Show(null);

However, form.Show() does not work as described. Why? I realize I am passing an owner as the parameter, but the owner is null. So why does the form behave correctly?

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

2 Answers2

10

Note that Show() is a method on the Control class and Show(IWin32Window) is a method on the Form class. This is the baked-in behavior of the Show(IWin32Window) method -- if the owner is null, the active window is used as the owner. Control.Show() has no concept of Owner. You can confirm via the MS reference source or a decompiler.

IntPtr hWndActive = UnsafeNativeMethods.GetActiveWindow();
IntPtr hWndOwner = owner == null ? hWndActive : Control.GetSafeHandle(owner); 
roken
  • 3,946
  • 1
  • 19
  • 32
  • @P.Brian He just means that if you use `Show(this)` for example, it would show the new window as a *child* of the current window. Otherwise, when you use `Show()` which is `Show(null)`, it will be without parent window. A parent window is useful in some cases, such as when you want to prevent user from interacting with parent window while the child window is shown. –  Oct 19 '12 at 20:50
  • @Desolator - That was my assumption too. Evidently (from the answers) Show() and Show(null) are not calling the same logic at all. – P.Brian.Mackey Oct 19 '12 at 20:52
  • @Desolator Show() != Show(null) – roken Oct 19 '12 at 20:53
  • @Desolator, actually, Show() is NOT the same as Show(null). Show() is on the Control class, while Show(IWin32Window owner) is on the Form class. Thus the different behaviors. – Luc Morin Oct 19 '12 at 20:53
2

When you pass null as the owner window then you force the Show(owner) method overload to go find an owner by itself. It will pick the active window. That's usually the one you want but not always. There are few good reasons to spin that wheel of fortune.

I don't get the "show() doesn't work" part of the question. If you call Show() without argument then the form will not have an owner.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • I'm hooking into a 3rd party application that's running unmanaged code. The window that I want to set as Parent is not available in Application.OpenForms. But...this "active window" trick does work and appears to be able to grab an unmanaged window as the parent. – P.Brian.Mackey Oct 19 '12 at 20:53