Message box that can center on parent form
When using the built in MessageBox class to show message you are not able to center the dialog based on the parent form. This leads to that the dialog normaly popup in the center of the screen even if the application it’s executed only cover the upper right corner for example. The solution is simple to create our own MessageBox clone with this added functionality. I was also missing a possibility to show a self closing message. So I could for example give the user 10 seconds to respond to the message, after that I would simple close the message dialog and use the default response.
To start we need to create a Form with below properies set to get a similar look and feel as MesssageBox (source code can be found int the bottom)
FormBorderStyle = FixedSingle
MaximizeBox = false
MinimizeBox = false
ShowIcon = false
ShowInTaskBar = false
We also need to add a few buttons and labels to get this result.
The key code to get the dialog to center ower the parent is this
messageDialog.Location = new Point(parentForm.Location.X + ((parentForm.Size.Width - messageDialog.Width)/2), parentForm.Location.Y + ((parentForm.Size.Height - messageDialog.Height)/2)); messageDialog.StartPosition = FormStartPosition.Manual; |
The countdown functionality is simple a Timer that fire of an event once a second to update the countdown, and when the countdown reach zero the dialog will close and return the default return value.
Se the complete code here. MessageDialogDemo