Solved

Restricting C# Application to one instance

Posted on 2011-09-12
7
1,291 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
Comment Utility
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
Comment Utility
0
 
LVL 15

Expert Comment

by:Russell_Venable
Comment Utility

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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 1

Assisted Solution

by:Temizh
Temizh earned 150 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

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

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

772 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

11 Experts available now in Live!

Get 1:1 Help Now