Solved

Restricting C# Application to one instance

Posted on 2011-09-12
7
1,336 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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Regarding swagger API 1 37
C# Service FileSystemwatcher isse 9 46
C# Windows app updating JSON file error. 9 39
locate sql commands in C# visual studio Project 6 44
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

733 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