I have a Visual C# 2010 application, and it has one main form called MainWnd
with other tool windows and dialogs. I want the other tool windows to be able to 'talk' to the main form, and call its methods. But that requires an instance of MainWnd
, and since there will only be one of these forms created at any given time there is no reason while I should enumerate through all instances of MainWnd
or look for the first one. So I want my main application form MainWnd
to be a singleton so other windows can easily call code from it.
Here is the code of the main form that I would like to make a 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 accomplish this?