65.9K
CodeProject is changing. Read more.
Home

MessageBox Wrappers for Windows Forms

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Oct 7, 2010

CPOL
viewsIcon

22305

downloadIcon

14

Use less code in your business logic for messages to the UI

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.

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

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);
}
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.

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

History

  • 20th December, 2020: Initial version