I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the application is run and the user didn't close the first instance of the application that is being run and need to run a next instance so it should appear the first instance and not opening new one.
can any one help me how to do that?
thanks in advance
I often solve this by checking for other processes with the same name. The advantage/disadvantage with this is that you (or the user) can "step aside" from the check by renaming the exe. If you do not want that you could probably use the Process-object that is returned.
It depends on your need, I think it's handy to bypass the check witout recompiling (it's a server process, which sometimes is run as a service).
The VB.Net team has already implemented a solution. You will need to take a dependency on Microsoft.VisualBasic.dll, but if that doesn't bother you, then this is a good solution IMHO. See the end of the following article: Single-Instance Apps
Here's the relevant parts from the article:
1) Add a reference to Microsoft.VisualBasic.dll 2) Add the following class to your project.
Open Program.cs and add the following using statement:
Change the class to the following:
I'd use a
Mutex
for this scenario. Alternatively, aSemaphore
would also work (but aMutex
seems more apt).Here's my example (from a WPF application, but the same principles should apply to other project types):
Assuming you are using C#
Edit : After the question was amended to include c#. My answer works only for vb.net application
select the Make single instance application check box to prevent users from running multiple instances of your application. The default setting for this check box is cleared, allowing multiple instances of the application to be run.
You can do this from Project -> Properties -> Application tab
Source
We had exactly the same problem. We tried the process approach, but this fails, if the user has no right to read information about other processes, i.e. non-admins. So we implemented the solution below.
Basically we try to open a file for exclusive reading. If this fails (because anohter instance has already done this), we get an exception and can quit the app.