Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

MessageBox Wrappers for Windows Forms

5.00/5 (2 votes)
3 Sep 2013CPOL 22.3K   14  
Use less code in your business logic for messages to the UI
Provides simple wrapper methods to display dialogs to user which is usually done with inline MessageBox in a form while this code moves that code to a code module for VB.NET or static class for C#

See the following GitHub repository, specifically in the following module.

Add either the class for C# or for VB.NET, add the code module to a project and use them.

This functionality can be placed into functions that are a) easier to read b) take less time to type as shown below:
Taking it one step further, place the code into My.NameSpace which makes locating the wrappers easier.

SQL
If My.Dialogs.Question("Continue", "Question") Then
   Close()
End If

How to use in a project, simply add the following code module to a project.

VB.NET/C# Versions

C#
public static class CommonDialogs
{
    public static bool Question(string text) =>
        (MessageBox.Show(text, "Question", 
            MessageBoxButtons.YesNo, MessageBoxIcon.Question, 
            MessageBoxDefaultButton.Button2) == DialogResult.Yes);
    public static bool Question(string text, string title) =>
        (MessageBox.Show(text, title, 
            MessageBoxButtons.YesNo, MessageBoxIcon.Question, 
            MessageBoxDefaultButton.Button2) == DialogResult.Yes);
}
VB.NET
Public Module CommonDialogs
    Public Function Question(text As String) As Boolean
        Return (MessageBox.Show(text, "Question",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button2) = DialogResult.Yes)
    End Function
    Public Function Question(text As String, title As String) As Boolean
        Return (MessageBox.Show(text, title,
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button2) = DialogResult.Yes)
    End Function
End Module

For the C# version, add the following static using statement, note it's recommended to place classes in a folder named classes (as done in the using statement below) although that is optional.

C#
using static yourNamespace.Classes.CommonDialogs;
C#
if (Question("Copy script to Windows Clipboard?"))
{
    Clipboard.SetText("Just pasted");
}

History

  • 20th December, 2020: Initial version

License

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