I want to create a custom message box for a program so I added a windows form item. I would like it to behave like MessageBox in that it is static and I just call MessageBox.Show(a, b, c, ...). In the forms designer, however, I don't see how I can make it static. Can I just add static to the code? Is there a property setting I'm missing in the designer mode?
Thanks!
MessageBox is not a static class, the Show method however is. Make Show static, in code. E.g.
public class MyMessageBox : Form
{
    public static int MyShow()
    {
        // create instance of your custom message box form
        // show it
        // return result 
    }
}
                        It is a regular class with one method as static which instantiate new instance and act.
public class MyMessageBox
{
   public static MyResult Show(params)
   {
       var myMessageBox = new MyMessageBox();
       myMessageBox.Message = params ...
       return  myMessageBox.ShowDialog();
   }
}
                        Add a static method to your form that displays itself and returns a DialogResult:
public partial class MyMessageBoxForm : Form {
  public static DialogResult Show(string message) {
    using (MyMessageBoxForm form = new MyMessageBoxForm(message)) {
      return form.ShowDialog();
    }
  private MyMessageBoxForm(string message) {
    // do something with message
  }
}
                        If you want create static Form1 for access to it without object reference, you can change Program.cs:
public class Program
{
    public static Form1 YourForm; 
    [STAThread]
    static void Main(string[] args)
    {
        using (Form1 mainForm = new Form1())
        {
            YourForm = mainForm;
            Application.Run(mainForm);
        }
        YourForm = null;
    }
}
and call Form1 class methods from any place of your program:
Program.YouForm.DoAnything();
Do not forget to call Invoke for access from other threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With