Results 1 to 15 of 15

Thread: Creating a Single Instance of your Application

Threaded View

  1. #11
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Allowing only once instance of your application

    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:
    1. static void Main()
    2.         {
    3.             Application.EnableVisualStyles();
    4.             Application.SetCompatibleTextRenderingDefault(false);
    5.            
    6.             int count = CheckForRunningInstances();
    7.  
    8.             if (count <= 1)
    9.             {
    10.                 Application.Run(new Form1());
    11.             }
    12.             else
    13.             {
    14.                 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);
    15.                 Application.Exit();
    16.             }
    17.  
    18.         }
    19.         private static int CheckForRunningInstances()
    20.         {
    21.  
    22.             string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
    23.             string appName = parts[parts.Length - 1];
    24.  
    25.             string query = "select name from CIM_Process where name = '" + appName + "'";
    26.  
    27.             System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
    28.  
    29.             int hInstCount = 0;
    30.  
    31.             foreach (System.Management.ManagementObject item in searcher.Get())
    32.             {
    33.                 hInstCount++;
    34.                 if (hInstCount > 1) break;
    35.             }
    36.             return hInstCount;
    37.         }
    Last edited by Paul M; Sep 11th, 2007 at 01:40 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width