Solved

Restricting C# Application to one instance

Posted on 2011-09-12
7
1,309 Views
Last Modified: 2012-06-27

Hi,

I would like to restrict my C# Winforms application to one instance per PC only?

Is there an elegant way of doing this? Programmatic or other.

Thanks in advance.

0
Comment
Question by:Ibs
7 Comments
 
LVL 15

Assisted Solution

by:navneethegde
navneethegde earned 50 total points
ID: 36521706
Hi!

check this!
http://www.ai.uga.edu/mc/SingleInstance.html


Best way is to check enumerated the running process and
check whether your process is running  if found then there is already one instance running  else
run your startup form

Thanks!
0
 
LVL 15

Expert Comment

by:navneethegde
ID: 36521713
0
 
LVL 15

Expert Comment

by:Russell_Venable
ID: 36529483

This is essentially what I use. This page shows a proper example of usage.

private Mutex mutex;
private string mutexName = "Todo3.0Mutex";

http://joelbennett.wordpress.com/2007/04/14/using-a-mutex-to-prevent-multiple-copies-of-an-application-from-runningc/

 

 
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 1

Assisted Solution

by:Temizh
Temizh earned 150 total points
ID: 36532280
You should mutex and process check together:

1: Mutex:
         public From1()
        {
            System.Threading.Mutex mutex = new System.Threading.Mutex(false, "Local\\MyAppName", out firstInstance);
            if (firstInstance && InstanceRunning())
            {
                InitializeComponent();
                Cursor.Hide();
            }
            else
            {
                this.Close();
            }
        }

Open in new window


2. process name:

private bool InstanceRunning
        {
            get
            {
                string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;

                System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(strProcessName);

                return (processes.Length > 1);

            }
        }

Open in new window


Mutex checks thread which helps you by prevent to run more instances of a windows form running on same process, the second one prevents to run different processes. together they prevent program to run more than one instance.
0
 
LVL 12

Expert Comment

by:starlite551
ID: 36532386
Here is a very useful link using Mutex Class :

http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx
0
 
LVL 12

Accepted Solution

by:
starlite551 earned 300 total points
ID: 36532396
Use this code :
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.IO;

namespace SingleInstance
{
	/// <summary>
	/// Summary description for SingleApp.
	/// </summary>
	public class SingleApplication
	{
		public SingleApplication()
		{

		}
		/// <summary>
		/// Imports 
		/// </summary>
	
		[DllImport("user32.dll")]
		private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

		[DllImport("user32.dll")]
		private static extern int SetForegroundWindow(IntPtr hWnd);

		[DllImport("user32.dll")]
		private static extern int IsIconic(IntPtr hWnd);

		/// <summary>
		/// GetCurrentInstanceWindowHandle
		/// </summary>
		/// <returns></returns>
		private static IntPtr GetCurrentInstanceWindowHandle()
		{    
			IntPtr hWnd = IntPtr.Zero;
			Process process = Process.GetCurrentProcess();
			Process[] processes = Process.GetProcessesByName(process.ProcessName);
			foreach(Process _process in processes)
			{
				// Get the first instance that is not this instance, has the
				// same process name and was started from the same file name
				// and location. Also check that the process has a valid
				// window handle in this session to filter out other user's
				// processes.
				if (_process.Id != process.Id &&
					_process.MainModule.FileName == process.MainModule.FileName &&
					_process.MainWindowHandle != IntPtr.Zero)    
				{
					hWnd = _process.MainWindowHandle;
					break;
				}
			}
			return hWnd;
		}
		/// <summary>
		/// SwitchToCurrentInstance
		/// </summary>
		private static void SwitchToCurrentInstance()
		{    
			IntPtr hWnd = GetCurrentInstanceWindowHandle();
			if (hWnd != IntPtr.Zero)    
			{    
				// Restore window if minimised. Do not restore if already in
				// normal or maximised window state, since we don't want to
				// change the current state of the window.
				if (IsIconic(hWnd) != 0)
				{
					ShowWindow(hWnd, SW_RESTORE);
				}

				// Set foreground window.
				SetForegroundWindow(hWnd);
			}
		}

		/// <summary>
		/// Execute a form base application if another instance already running on
		/// the system activate previous one
		/// </summary>
		/// <param name="frmMain">main form</param>
		/// <returns>true if no previous instance is running</returns>
		public static bool Run(System.Windows.Forms.Form frmMain)
		{
			if(IsAlreadyRunning())
			{
				//set focus on previously running app
				SwitchToCurrentInstance();
				return false;
			}
			Application.Run(frmMain);
			return true;
		}

		/// <summary>
		/// for console base application
		/// </summary>
		/// <returns></returns>
		public static bool Run()
		{
			if(IsAlreadyRunning()) 
			{
				return false;
			}
			return true;
		}

		/// <summary>
		/// check if given exe alread running or not
		/// </summary>
		/// <returns>returns true if already running</returns>
		private static bool IsAlreadyRunning()
		{
			string strLoc = Assembly.GetExecutingAssembly().Location;
			FileSystemInfo fileInfo = new FileInfo(strLoc);
			string sExeName = fileInfo.Name;
			bool bCreatedNew;

			mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
			if (bCreatedNew)
				mutex.ReleaseMutex();

			return !bCreatedNew;
		}
		
		static Mutex mutex;
		const int SW_RESTORE = 9;
	}
}

Open in new window

0
 

Author Comment

by:Ibs
ID: 36908787

Hi All, several good options here, I am currently trying these out.
Thanks for all your suggestions.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now