Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Static Form Added to Project?

Tags:

c#

forms

static

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!

like image 890
john Avatar asked Oct 27 '11 16:10

john


4 Answers

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 
    }
}
like image 74
Paul Sasik Avatar answered Sep 28 '22 21:09

Paul Sasik


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();
   }
}
like image 23
Mohamed Abed Avatar answered Sep 28 '22 21:09

Mohamed Abed


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
  }

}
like image 23
C-Pound Guru Avatar answered Sep 28 '22 21:09

C-Pound Guru


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.

like image 23
user3424037 Avatar answered Sep 28 '22 22:09

user3424037