943,369 Members | Top Members by Rank

Ad:
  • C# Code Snippet
  • Views: 3533
  • C# RSS
1

Check for Single-Instance

by on Aug 25th, 2008
A simple way to check if the current C# program is the only instance of itself running.
C# Code Snippet (Toggle Plain Text)
  1. private bool IsSingleInstance()
  2. {
  3. foreach (Process process in Process.GetProcesses())
  4. {
  5. if (process.MainWindowTitle == this.Text)
  6. return false;
  7. }
  8. return true;
  9. }
Comments on this Code Snippet
Nov 2nd, 2009
0

Re: Check for Single-Instance

this give error....
In foreach line (in process)
always mention namespace which is required and that place where code to be paste
Light Poster
ashishkumar008 is offline Offline
45 posts
since Nov 2009
Nov 2nd, 2009
1

Re: Check for Single-Instance

Simple, yes... but not something I'd allow into production code. See these links for some discussion.

Here's an alternative... first, a method to try to create a mutex unique to the application:

C# Syntax (Toggle Plain Text)
  1. private Mutex GetSingleInstanceMutex()
  2. {
  3. bool createdNewMutex;
  4.  
  5. Mutex mutex = new Mutex(false, @"Global\" + SomethingUnique, out createdNewMutex);
  6.  
  7. if (!createdNewMutex)
  8. {
  9. mutex = null;
  10. }
  11.  
  12. return mutex;
  13. }

SomethingUnique should be something unique to the application, for example, the assembly GUID.

Here's how you'd use the method:

C# Syntax (Toggle Plain Text)
  1. using (Mutex mutex = GetSingleInstanceMutex())
  2. {
  3. if (mutex != null)
  4. {
  5. // This is the only running instance; go ahead and run the application.
  6. }
  7. else
  8. {
  9. // Another instance is running; notify user and quit.
  10. }
  11. }
Posting Pro in Training
gusano79 is offline Offline
475 posts
since May 2004
Nov 3rd, 2009
0

Re: Check for Single-Instance

Request:-
i want to use flash file in webbrowser like other resources like picture
i do not want to use full path (c:\programfile\).
can u post full c# code
please
Light Poster
ashishkumar008 is offline Offline
45 posts
since Nov 2009
Message:
Previous Thread in C# Forum Timeline: Link List in C#
Next Thread in C# Forum Timeline: voice chat over LAN





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC