Can I create a Singleton form?

I have a Visual C # 2010 application and it has one main form called MainWnd with other windows and tool dialogs. I want other tool windows to β€œtalk” to the main form and call its methods. But this requires an instance of MainWnd , and since there will be only one of these forms created at any given time, there is no reason for me to list all instances of MainWnd or search for the first one. Therefore, I want my main MainWnd application MainWnd be single, so other windows can easily invoke code from it.

Here is the code of the main form that I would like to make singleton:

 using System; using System.ComponentModel; using System.Windows.Forms; namespace MyLittleApp { public partial class MainWnd : Form { public MainWnd() { InitializeComponent(); } public void SayHello() { MessageBox.Show("Hello World!"); // In reality, code that manipulates controls on the form // would go here. So this method cannot simply be made static. } } } 

I am looking to be able to call SayHello() from another form simply by writing:

 MainWnd.SayHello(); 

How could I do this?

+4
source share
3 answers

You could probably find a way to make the main window a singleton, but this is not the best way to achieve the desired result, and this is not a suitable situation in which you can use the singleton pattern.

If all other tool windows / dialogs are encapsulated in the main window, then an event is a much better template for communication.

Inner windows / dialogs create events to present a β€œrequest” for the main window to do something. Connect the main window to these events and do the work using event handlers.

By avoiding the singleton approach, you avoid the difficulty of testing a singleton and also avoid extensive explicit circular links, where not only the main window has links to encapsulated windows / dialogs, but they, in turn, have explicit links back to the main window.

+3
source

See below.

 using System; using System.ComponentModel; using System.Windows.Forms; namespace MyLittleApp { public partial class MainWnd : Form { public static MainWnd Instance; public MainWnd() { Instance = this; InitializeComponent(); } public void SayHello() { MessageBox.Show("Hello World!"); // In reality, code that manipulates controls on the form // would go here. So this method cannot simply be made static. } } } 

Now you can use it anywhere in your code by calling MainWnd.Instance All its members are also accessible to the instance.

+1
source

Can you do this.

  public MainWnd Instance = new MainWnd(); 

Then access as MainWnd.Instance.SayHello() .

Replace the following calls

 MainWind instance = new MainWnd(); 

For

  MainWnd instance = MainWnd.Instance; 

I'm not sure how the Visual Studio designer would react by adding the constructor as a private one. But if this does not allow it, it will be a Visual Studio problem, not a language / compiler problem.

0
source

All Articles