Centering MessageBox, Common DialogBox or Form on applications






4.83/5 (15 votes)
Mar 30, 2005
1 min read

179817

5141
Simple component to center any MessageBox, Form or CommonDialog on applications.
Introduction
The .NET standard MessageBox
is centered on the screen area, not on the application. This code contains a simple component which uses a hook to center the MessageBox
and also other CommonDialog or Forms on the application area.
Background
This article will not explain in detail how to use a hook in a window. The component will add a WH_CALLWNDPROC
hook looking for a WM_INITDIALOG
message before opening the dialog. When this message occurs, the window is centered on the owner window, or the active window if the owner window is null
.
Using the code
Using the code is very easy. It is the same as using the standard MessageBox
.
The following static
methods are available:
DlgBox.ShowDialog(...)
For CommonDialog and Forms.
MsgBox.Show(...)
For standard
MessageBox
, you can define the caption.AppBox.Show(...)
For standard
MessageBox
withApplication.ProductName
as caption.ErrBox.Show(...)
For standard error
MessageBox
with message or exception.
Example: the following code displays a centered OpenFileDialog
:
DlgBox.ShowDialog(new OpenFileDialog());
Example: the following code display a centered exception error message:
try
{
...
}
catch (Exception ex)
{
ErrBox.Show(ex);
}
It is possible to add standard buttons or icons. All the MessageBox
methods are wrapped.
Example: the following example displays a centered rich message box:
AppBox.Show("Rich Application Box",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
Points of Interest
There is a base class WindowsHook
to create other hooks. The WndProcRetHook
is based on this class. You can use this base class to create your own hook.
There is also a TrueScreenRect
property to retrieve the true screen size on multiscreen display.
History
This version is working well since 1.1.2003.