Click here to Skip to main content
15,879,096 members
Articles / Desktop Programming / Windows Forms

FlexibleMessageBox – A Flexible Replacement for the .NET MessageBox

Rate me:
Please Sign up or sign in to vote.
4.98/5 (90 votes)
19 Dec 2014CPOL6 min read 260.9K   12.2K   119   140
Use FlexibleMessageBox.Show to seamlessly replace your usages of MessageBox.Show and get more features in a single class you can easily add to your project

Introduction 

When you design a user interface using classic Windows Forms, you normally use the .NET MessageBox to give short information feedbacks or let the user make choices. In my latest project, I also needed simple dialogs to display status messages after processing some server operations. These messages were usually quite short, something like "everything was processed successfully". So “why create my own dialog”, I thought and decided to use the standard MessageBox to do the job. 

The Problem

Everything worked well and my program kept growing for a while. I added some bigger batch operations which consist of many server operations. Every operation had its – usually quite short – message but also could produce a short error report. All of these messages together could add to quite big “status reports”.

When I first saw the results. they looked like this:

Image 1

Yes, the MessageBox did resize itself to fit my contents, but I could not see any of my buttons at the bottom, because it was cropped at the bottom. But not enough: Not all contents are reachable, because the vertical scrollbar was missing.

This was not acceptable for me, so I was thinking about creating an own dialog to display my various kinds of messages. The more I thought about it, the less I wanted to design a dialog specially tailored to the application, especially because I did not want to change all usages of MessageBox.Show(…) in my code.

The Solution: A Flexible Messagebox

I was searching for a replacement of my standard MessageBox in the web. But although I found very useful things, none of the solutions made me really happy. I, first of all, wanted a MessageBox-Replacement which should be resizable and no bunch of code, which would have been overdone for me. So I ended up programming a substitution to fit my own needs.

Features

This is an abstract of the features provided by FlexibleMessageBox:

  • It can be simply used instead of MessageBox since all important static Show functions are supported
  • It is small, only one source file, which could be added easily to each solution
  • It can be resized and the content is correctly word-wrapped
  • It tries to auto-size the width to show the longest text row
  • It never exceeds the current desktop working area
  • It displays a vertical scrollbar when needed
  • It supports hyperlinks in the text

Appearance

Using the FlexibleMessageBox, the results from above could now look like this:

Image 2

But the appearance of the FlexibleMessageBox can also look like:

Image 3

Or using another font like so:

Image 4

Using the FlexibleMessageBox

Integration Into Your Project

To use the FlexibleMessageBox in your code, the following simple steps are suggested:

  1. Download the FlexibleMessageBox.cs source file (or the demo project).
  2. Add the FlexibleMessageBox.cs source file to your solution.
  3. Add using JR.Utils.GUI.Forms to your source file.

That’s all. Now you can use FlexibleMessageBox like (almost) every other MessageBox.

Usage examples:

C#
FlexibleMessageBox.Show("Just a text");
FlexibleMessageBox.Show("A text", "A caption");

FlexibleMessageBox.Show("Some text with a link: www.google.com", 
                        "Some caption",
                        MessageBoxButtons.AbortRetryIgnore, 
                        MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button2);

var result = FlexibleMessageBox.Show("Know the answer to life the universe and everything?", 
            "One short question", 
            MessageBoxButtons.YesNo); //By the way: The answer is 42  :-)

Using the Demo Application

This is just a small Windows Forms application to demonstrate the features of the FlexibleMessageBox:

Image 5

The leftmost two buttons do show two variations of the FlexibleMessageBox with different parameters. The two buttons in the middle do show a sample for a text with many rows, first time with the .NET MessageBox and in contrast using the FlexibleMessageBox. You can test resizing the FlexibleMessageBox and watch the word wrapping and the vertical scrollbar. On the right side, you can change some static parameters (which are described below) to see how the appearance of all FlexibleMessageBoxes does change. Click the checkbox to use another font. Use the sliders to modify the maximum width and height.

Inside the Code

Decision: Provide the Code in a Single File

I know that I should have to split the code in more than one source file to keep it more readable and for terms of modularization. But I also know that I, for my part, was often annoyed when I wanted to use an external component and have to include many files for a simple component. So I decided to put this component in one single file that can be added to other projects easily.

Clean Interface

You may have noticed that the public interface of the FlexibleMessageBox is very clean:

Image 6

That’s because all relevant helper functions reside in an inner class FlexibleMessageBoxForm. See below for a short description of this class.

Static Show-Functions

These are the available Show-Functions, which are a subset of those in the original .NET MessageBox Show-Functions:

C#
#region Public show functions

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(string text)

/// <summary> 
/// Shows the specified message box.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="text">The text.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(IWin32Window owner, string text)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(string text, string caption)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(IWin32Window owner, string text, string caption)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(IWin32Window owner, 
       string text, string caption, MessageBoxButtons buttons)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <returns></returns>
public static DialogResult Show(string text, string caption, 
       MessageBoxButtons buttons, MessageBoxIcon icon)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(IWin32Window owner, string text, 
       string caption, MessageBoxButtons buttons, MessageBoxIcon icon)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButton">The default button.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(string text, string caption, 
  MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)

/// <summary>
/// Shows the specified message box.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="text">The text.</param>
/// <param name="caption">The caption.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButton">The default button.</param>
/// <returns>The dialog result.</returns>
public static DialogResult Show(IWin32Window owner, string text, string caption, 
  MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)

#endregion 

Static Parameters

There are a few static variables that contain settings used for all FlexibleMessageBox instances:

MAX_WIDTH_FACTOR

Defines the maximum width for all FlexibleMessageBox instances in percent of the working area.
Allowed values are minimal from 0.2 up to 1.0:

  • 0.2 means: The FlexibleMessageBox can be at most half as wide as the working area.
  • 1.0 means: The FlexibleMessageBox can be as wide as the working area.

The default value is 0.7 which is 70% of the working area width.

MAX_HEIGHT_FACTOR

Defines the maximum height for all FlexibleMessageBox instances in percent of the working area.

Allowed values are minimal from 0.2 up to 1.0:

  • 0.2 means: The FlexibleMessageBox can be at most half as high as the working area.
  • 1.0 means: The FlexibleMessageBox can be as high as the working area.

The default value is 0.9 which is 90% of the working area height.

Font

Defines the font that is used for all FlexibleMessageBox instances. The default value is SystemFonts.MessageBoxFont.

Inner Form Class FlexibleMessageBoxForm

The hidden inner class FlexibleMessageBoxForm is derived from Form and does arrange the needed GUI elements. The text is provided as a RichTextBox. Beyond, there are three buttons and the PictureBox for the icon – nothing magical.

Show-Function

The static Show function of <code>FlexibleMessageBoxForm is called by all Show-functions of FlexibleMessageBox. It is dealing with all the different given parameters and performs the following operations:

  • Creates a new instance of the FlexibleMessageBox form
  • Binds the caption and the message text
  • Sets the buttons visibilities and texts
  • Sets a default button
  • Sets the dialogs icon. When no icon is used: Corrects the placement and width of rich text box
  • Sets the font for all controls, using the static FONT. When no font is set, it uses the standard SystemFonts.MessageBoxFont
  • Calculates the dialogs start size by trying to auto-size the width to show the longest text row
  • Sets the dialogs maximum size, using the statics for MAX_WIDTH_FACTOR and MAX_HEIGHT_FACTOR
  • Sets the dialogs start position when given. Otherwise, centers the dialog on the current screen
  • And last but not least: Shows the dialog
Helper Functions and Other Stuff

There are several small helper functions. Please discover them on your own. I tried to document it well and used code regions to increase the readability.

History

Version 1.3 - 19. December 2014 (Bugfixes)

  • Added refactoring function GetButtonText()
  • Used CurrentUICulture instead of InstalledUICulture
  • Added more button localizations. Supported languages are now: ENGLISH, GERMAN, SPANISH, ITALIAN
  • Added standard MessageBox handling for "copy to clipboard" with <Ctrl> + <C> and <Ctrl> + <Insert>
  • Tab handling is now corrected (only tabbing over the visible buttons)
  • Added standard MessageBox handling for ALT-Keyboard shortcuts

Version 1.2 - 10. August 2013

  • Do not ShowInTaskbar anymore (original MessageBox is also hidden in taskbar)
  • Added handling for Escape-Button
  • Adapted top right close button (red X) to behave like MessageBox (but hidden instead of deactivated)

Version 1.1 - 14. June 2013

  • Some Refactoring
  • Added internal form class
  • Added missing code comments, etc.

Version 1.0 - 15. April 2013

  • Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Softwarelösungen Reichert
Germany Germany
I am a freelancer developer since 2005. Prior to that I worked for a small software company beginning in 1998. My origins in the software sector were in 1980s as I programmed assembler on the good old C64 and dreamt of being a game developer.

Freelance profiles (all in German):
> Profile documents (profile, project list) here: http://www.jreichert.de/5533.html
> GULP profile (GULP ID: 71039): http://www.gulp.de/Profil/jreichert.html

Contact form:
> http://www.jreichert.de/5323/index.html

Comments and Discussions

 
QuestionDialogResult always Cancel, Dialog never shown Pin
nothingofvalue7-Jun-19 11:06
nothingofvalue7-Jun-19 11:06 
AnswerRe: DialogResult always Cancel, Dialog never shown Pin
nothingofvalue9-Jun-19 11:33
nothingofvalue9-Jun-19 11:33 
QuestionHow to make the box not resizable by the user? Pin
Furuchi9-May-19 20:03
Furuchi9-May-19 20:03 
AnswerRe: How to make the box not resizable by the user? Pin
Member 1497575426-Oct-20 9:24
Member 1497575426-Oct-20 9:24 
QuestionWould be nice if the caption could change font too Pin
MrBjorn8-May-19 4:09
MrBjorn8-May-19 4:09 
GeneralMy vote of 4 Pin
Jim Fell22-Apr-19 7:31
Jim Fell22-Apr-19 7:31 
SuggestionSetting Background Color Pin
Jim Fell22-Apr-19 4:50
Jim Fell22-Apr-19 4:50 
QuestionResizing form after it is displayed Pin
otalado17-Mar-19 23:10
otalado17-Mar-19 23:10 
There are some cases when resizing the box after it is displayed is not desirable. Unfortunately I can't find the way to disable it. I did few things with your control successfully, but this one escapes me so far. Can you make any suggestions?
AnswerRe: Resizing form after it is displayed Pin
otalado18-Mar-19 22:13
otalado18-Mar-19 22:13 
GeneralMy vote of 5 Pin
Member 123159926-Aug-18 22:23
Member 123159926-Aug-18 22:23 
QuestionFlexibleMessageBox - Centre of Parent Pin
Geoffrey H Wood12-Jun-18 9:55
Geoffrey H Wood12-Jun-18 9:55 
AnswerRe: FlexibleMessageBox - Centre of Parent Pin
Jim Fell22-Apr-19 7:28
Jim Fell22-Apr-19 7:28 
QuestionflexibleMessageBob on TopMost Form Pin
mateusz_lozo22-Apr-18 10:02
mateusz_lozo22-Apr-18 10:02 
AnswerRe: flexibleMessageBob on TopMost Form Pin
mateusz_lozo23-Apr-18 8:42
mateusz_lozo23-Apr-18 8:42 
SuggestionAdding Copy Context Menu to Flexible Message Box Pin
nitrous_00729-Jan-18 7:11
nitrous_00729-Jan-18 7:11 
QuestionHow to add MessageBoxOptions? Pin
Member 111156891-Jan-18 0:59
Member 111156891-Jan-18 0:59 
AnswerRe: How to add MessageBoxOptions? Pin
Member 111156891-Jan-18 1:10
Member 111156891-Jan-18 1:10 
QuestionIs there a VB.Net version of this FlexibleMessageBox? Pin
FACKiko27-Sep-17 5:12
FACKiko27-Sep-17 5:12 
AnswerRe: Is there a VB.Net version of this FlexibleMessageBox? Pin
phil.o22-Oct-17 2:24
professionalphil.o22-Oct-17 2:24 
GeneralRe: Is there a VB.Net version of this FlexibleMessageBox? Pin
JReichert1-Feb-18 2:42
professionalJReichert1-Feb-18 2:42 
GeneralRe: Is there a VB.Net version of this FlexibleMessageBox? Pin
ichwandepok12-Aug-20 21:07
ichwandepok12-Aug-20 21:07 
AnswerRe: Is there a VB.Net version of this FlexibleMessageBox? Pin
massimo ravaglia17-Feb-18 8:17
massimo ravaglia17-Feb-18 8:17 
SuggestionMy Vote is 5 Pin
Alex Averbuch10-Sep-17 20:05
Alex Averbuch10-Sep-17 20:05 
GeneralRe: My Vote is 5 Pin
JReichert1-Feb-18 2:44
professionalJReichert1-Feb-18 2:44 
GeneralMy vote of 5 Pin
Fiwel17-Jul-17 14:52
Fiwel17-Jul-17 14:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.