I would like to Show my Messagebox in the center of its parent form. if i move the form and show the messagebox, it always show in the center of the desktop. i want it to appear along with the form. Can you give me some tricks and advice?
Set the owner of the message box window to your window (using the first parameter of .Show()
), instead of not setting an owner.
See here for a reference.
I have done this before in C#. Here's what I remember.
Define a class:
public class IWindowWrapper : System.Windows.Forms.IWin32Window
{
public IWindowWrapper(IntPtr handle)
{
this.Handle= handle;
}
public IntPtr Handle
{
get;
set;
}
}
Define a class based on MessageBox. Create a class based on MessageBox and create a new Show method :
public string Show(IWin32Window owner)
{
if(owner == null)
{
this.ShowDialog();
}
else
{
//parentWindow.
this.StartPosition = FormStartPosition.CenterParent;
this.ShowDialog(owner);
}
}
In your calling code (here it is assumed to be a winform and msgBox is based on the new message box class) call the new Show method and pass an IWindowWrapper instance on Show e.g.
msgBox.Show(new IWindowWrapper(this.Handle))
The best way to do this is to use Window Hooks and center the message box yourself. There is a perfect article which shows this usage.
You can find it here: http://www.codeproject.com/KB/dialog/CenterDialog.aspx
You can also use the class in your application without diving in too deep to find out how it actually works.