Reputation: 2066
I have a application in which i have several forms. In that forms, I have a System Settings form. I have to open this form from the menu as well as a shortcut created on the desktop.
I am able to open the form from 2 places individually. But the problem is, It's opening two separate instance of the same form. it means, first, i have clicked on menu to open the form.Now my Form instance is created and it is displayed on the screen. But whenever i click on my desktop icon, It's creating another instance of the same form instead of displaying the same form. . So it means it's displaying two instances of the same form.
But i have display one form only. I have tried and googled in the net also. I didn't find any information.
Can anybody please help me to fix this issue. Any kind of suggestion will be really helpful to me.
Upvotes: 2
Views: 3772
Reputation: 514
Sounds like you need a modified version of the Singleton design pattern. Try having a public static method within the class that internally calls the constructor for the form. Then as someone suggested use a counter variable to keep track of how may times that static method is called thus giving you a metric you can use to ensure only the desired number if instance are created.
Upvotes: 0
Reputation: 2066
I have used semaphor concept to control this. Whenever the form is opened i am writing an entry into registry. Once the form is closed i am removing this entry.
So, whenever i try to open the form, it will check the registry entry. Based on that it will open the form.
Upvotes: 0
Reputation: 45101
You need a single instance. This construct is already available within the .Net framework. Just check out this post from Hanselman.
Note: I know that the namespace of this class is VisualBasic. But that shouldn't hinder you to use it in your C# application. It's just the name of a namespace. It doesn't meant anything about its functionality. (Microsoft had it better named Foo. In that case it would be much more popular.)
Upvotes: 3
Reputation: 9279
To throw in one more link, this post seems to cover (my understanding of) what you are trying to do.
http://dotnetperls.com/single-instance-windows-form
Upvotes: 0
Reputation: 4280
You have to implement some kind of locking mechanism to allow only one instance of your program running. I guess your System Settings program could check if other instances are running on computer on program launch, if so terminate, otherwise start a new instance.
Upvotes: 0
Reputation: 2142
Sounds to me, that you need a mutex to control that only one application instance is running at a given time.
See http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx for further details
Upvotes: 2