<< Click to Display Table of Contents >> WinForms: How to center a MessageBox over its parent window C# |
|
Windows Forms is old, but it's still widely used. The MessageBox.Show() method puts the message box in the center of the screen instead of in front of its parent window. This is very annoying, especially on a large screen. Microsoft should have provided an option for this. Many people have struggled with this problem over the years. Here is a very simple solution.
The solutions on Internet which center the dialog box over the parent window usually use a derived MassageBoxEx class with a 'windows hook'. My method just intercepts the WM_ACTIVATE message that's sent to the parent window when the child window (the message box) is activated, so you don't need to use a non-standard MessageBox class.
The code below centers ALL the child windows, which is OK for many applications. You can easily easily limit it to certain types of window by examining the class name or title text, or even send the window a WM_USER message to ask if it should be centered or not, so you can disable this feature for your own windows.
|