Custom Messagebox

9 times out of 10 the standard Windows Forms messagebox will do, but for those occasions it won’t, it’s pretty straight forward to design your own. I have an enum ‘MyMessageBoxButtons’ set up to accept ‘ok’ and ‘okCancel’, I have also set the OK button to fill the width of it’s parent panel if it is the only button to be displayed (this messagebox form is being displayed full screen in a mobile application), but you get the idea.


public partial class MyMessagebox : Form
{
    private static MyMessagebox messageBox;
    private static DialogResult messageboxResult;

    public MyMessagebox ()
    {
        InitializeComponent();
    }

    public static DialogResult Show(string messageText)
    {
        messageBox = new MyMessagebox ();
        messageBox.lbMessageboxMessage.Text = messageText;
        ShowButtons(messageBox, MyMessageBoxButtons.Ok);
        messageBox.ShowDialog();

        return messageboxResult;
    }

    public static DialogResult Show(string messageText, string messageCaption, MyMessageBoxButtons buttons)
    {
        messageBox = new myMessagebox();
        messageBox.lbMessageboxMessage.Text = messageText;
        messageBox.lbMessageboxCaption.Text = messageCaption;
        ShowButtons(messageBox, buttons);
        messageBox.ShowDialog();

        return messageboxResult;
    }
    
    private static void ShowButtons(MyMessageBox myMessageBox, MyMessageBoxButtons buttons)
    {
        myMessageBox.btnMessageboxOk.Enabled = true;
        myMessageBox.btnMessageboxOk.Visible = true;

        if (buttons != MyMessageBoxButtons.Ok)
        {
            myMessageBox.btnMessageboxCancel.Enabled = true;
            myMessageBox.btnMessageboxCancel.Visible = true;
        }
        else
        {
            myMessageBox.btnMessageboxOk.Width = myMessageBox.pnMessageboxDetail.Width;
        }
    }

    private void btnMessageboxOk_Click(object sender, EventArgs e)
    {
        messageboxResult = DialogResult.OK;
        messageBox.Close();
    }

    private void btnMessageboxCancel_Click(object sender, EventArgs e)
    {
        messageboxResult = DialogResult.Cancel;
        messageBox.Close();
    }        
}