Click here to Skip to main content
15,867,594 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 259.2K   12.1K   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

 
AnswerRe: Very nice! One issue with long lines that wrap Pin
SZLMCL18-Mar-17 9:50
SZLMCL18-Mar-17 9:50 
GeneralRe: Very nice! One issue with long lines that wrap Pin
massimo ravaglia17-Feb-18 8:16
massimo ravaglia17-Feb-18 8:16 
Praisevery nice Pin
BillW3327-Oct-16 3:46
professionalBillW3327-Oct-16 3:46 
QuestionHow to color the text message Pin
riscy24-Sep-16 7:16
riscy24-Sep-16 7:16 
SuggestionRe: How to color the text message Pin
JReichert26-Sep-16 3:25
professionalJReichert26-Sep-16 3:25 
BugJapanese Text Bug Pin
Alamer9920-Jul-16 21:34
Alamer9920-Jul-16 21:34 
GeneralRe: Japanese Text Bug Pin
JReichert20-Jul-16 21:43
professionalJReichert20-Jul-16 21:43 
GeneralRe: Japanese Text Bug Pin
Alamer9920-Jul-16 23:32
Alamer9920-Jul-16 23:32 
GeneralRe: Japanese Text Bug Pin
JReichert21-Jul-16 1:11
professionalJReichert21-Jul-16 1:11 
GeneralRe: Japanese Text Bug Pin
Alamer9921-Jul-16 2:30
Alamer9921-Jul-16 2:30 
GeneralRe: Japanese Text Bug Pin
Alamer9925-Jul-16 9:01
Alamer9925-Jul-16 9:01 
AnswerRe: Japanese Text Bug Pin
JReichert25-Jul-16 9:55
professionalJReichert25-Jul-16 9:55 
QuestionConfuserEx Pin
jojotjo10-Jun-16 7:25
jojotjo10-Jun-16 7:25 
AnswerRe: ConfuserEx Pin
JReichert12-Jun-16 2:49
professionalJReichert12-Jun-16 2:49 
GeneralRe: ConfuserEx Pin
jojotjo14-Jun-16 11:31
jojotjo14-Jun-16 11:31 
GeneralAlmost perfect Pin
Dzunisani16-May-16 20:57
Dzunisani16-May-16 20:57 
SuggestionRe: Almost perfect => [ScrollBar Appearance] Pin
JReichert16-May-16 21:53
professionalJReichert16-May-16 21:53 
GeneralMy vote of 5 Pin
hobo hoho4-May-16 6:56
hobo hoho4-May-16 6:56 
QuestionBug: Long Lines Pin
Metal4504-Apr-16 17:26
Metal4504-Apr-16 17:26 
QuestionBug: Empty Caption Pin
Metal4504-Apr-16 16:54
Metal4504-Apr-16 16:54 
GeneralMy vote of 5 Pin
Polinia29-Feb-16 0:50
Polinia29-Feb-16 0:50 
QuestionCaption Font? Pin
andy grant3-Dec-15 4:42
andy grant3-Dec-15 4:42 
SuggestionRe: Caption Font? Pin
JReichert3-Dec-15 11:01
professionalJReichert3-Dec-15 11:01 
Questiongreat work Pin
Member 1029443819-Sep-15 6:41
Member 1029443819-Sep-15 6:41 
AnswerRe: great work Pin
JReichert5-Oct-15 0:43
professionalJReichert5-Oct-15 0:43 

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.