如何防止表单再次打开。我创建了我的应用程序并安装了它,但是当我再次单击该图标时,应用程序再次打开,依此类推,如果我再次单击该图标,我该如何防止这种情况?
一段时间后,斯科特·汉塞尔曼(Scott Hanselman)做了一个很好的帖子 - 这就是链接
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.