开发者

How can i prevent the form from opening again?

开发者 https://www.devze.com 2023-03-30 15:44 出处:网络
How can i prevent the form from opening again.I made my application and installed it, however when i click on the icon again the application open once again and so on if i clicked on the icon again, h

How can i prevent the form from opening again.I made my application and installed it, however when i click on the icon again the application open once again and so on if i clicked on the icon again, how can i prev开发者_C百科ent that ?


Scott Hanselman did a good post on doing this a while back - here's the link


Try Mutex. Here is a good article on the subject:

http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

      Application.Run(new Form1());
   }
}


You can do it by Checking list of Currently Running Processes. If It is Duplicated, Kill Self. This will prevent Multiple Instances.

   Process[] pArry = Process.GetProcesses();   //Get Currently Running Processes   
   int Instance_Counter = 0; // To count No. of Instances

  foreach (Process p in pArry) 
       {         
          string ProcessName = p.ProcessName;   
        //Match the Process Name with Current Process (i.e. Check Duplication )
       //If So Kill self
        if(ProcessName == Process.GetCurrentProcess().ProcessName)                
         {              
            Instance_Counter++;   
        }    
           } 

    if(Instance_Counter>1)
    {
       //Show Error and Kill Yourself
    }


It's not the best way but fixed method of Swanand Purankar's as it mentioned before:

//I set Timer's interval to "250", it's personal
//Just don't forget to enable the timer
private void timer1_Tick(object sender, EventArgs e)
{
    var self = Process.GetCurrentProcess();
    foreach (var proc in Process.GetProcessesByName(self.ProcessName))
    {
        if (proc.Id != self.Id)
        {
            proc.Kill();
        }
    }
}

However with this way you can't set an error. If you want that:

private void Form1_Load(object sender, EventArgs e)
{
    if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
    {
        MessageBox.Show("Hey there opening multiple instances of this process is restricted!", "Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        this.Close();
    }
}

Still, the user can easily pass this by renaming the program. Using registry can help. But a hacker/developer still can get rid of this. Via using a process monitor.

0

精彩评论

暂无评论...
验证码 换一张
取 消