How to create AlwaysOnTop MDI child ?
A Question I was asked by someone was how to create an AlwaysOnTop MDI child window ?
So you have an MDI app that contains several children and you’re been trying to find a way to display an MDI child form behind the current active child. You don't want to have to call all of the other forms SendToBack methods because you want the user to have a more seamless experience. You might be wondering if there is a property or method in the Form class that will allow for it to become shown behind the active one, but there isn’t.
So what can you do ?
Here's how to set up an MDI application so that MDI childs operate normally, but some child windows always stay on top. (there is a simple trick … )
How do we’ll do it ?
1. The always-on-top child is not an MDI child ! – Don’t set its MdiPatent property
2. We will achieve the child’s behavior for this form by calling the win32 api SetParent( child.hwnd, parent.hwnd)
Follow these instructions to set up a simple demonstration:
1. Open visual studio
2. Create a windows application
3. Rename Form1 to MainForm and change the IsMdiContainer property to true.
4. Add two new Windows Forms to the project and name them frmMdiChild and frmAlwaysOnTop
5. Add the flowing lines to the MainForm load event:
frmMdiChild child1=new frmMdiChild();
child1.MdiParent=this;
child1.Show();
frmMdiChild child2=new frmMdiChild();
child2.MdiParent=this;
child2.Show();
frmAlwaysOnTop topform=new frmAlwaysOnTop();
topform.Show();
SetParent((int)topform.Handle,(int)this.Handle); <<< Here is the Magic :-)
6. Add declaration of the SetParent win32api to the MainForm class:
[DllImport("user32")] public static extern int SetParent(int hWndChild, int hWndNewParent) ;
7. Run the demo !
Shortcut :-)
Download the example from here