This will only allow one instance of your application, i use this code for a couple of my programs/services...
Make sure you maker a reference to the System.Management class
C# Code:
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); int count = CheckForRunningInstances(); if (count <= 1) { Application.Run(new Form1()); } else { System.Windows.Forms.MessageBox.Show("Another instance of this program is already running. Two instances cannot run at the same time", "Already running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Application.Exit(); } } private static int CheckForRunningInstances() { string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray()); string appName = parts[parts.Length - 1]; string query = "select name from CIM_Process where name = '" + appName + "'"; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query); int hInstCount = 0; foreach (System.Management.ManagementObject item in searcher.Get()) { hInstCount++; if (hInstCount > 1) break; } return hInstCount; }





Reply With Quote