Solved

Restricting C# Application to one instance

Posted on 2011-09-12
7
1,366 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

705 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