保证程序只有一个实例运行并且先将旧实例关闭再运行新实例
2007-12-10 14:03
465 查看
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
namespace MyClient
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//bool blnCreate;//Another method to make sure only one instance
//Mutex m = new Mutex(true, "MyClient", out blnCreate);
//if (blnCreate)
CloseRunningInstance();
Application.Run(new MainFrm());
}
//Close the existed instance of my application
static void CloseRunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Close the other process instance.
process.Kill();
process.WaitForExit();
}
}
}
}
}
}
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
namespace MyClient
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//bool blnCreate;//Another method to make sure only one instance
//Mutex m = new Mutex(true, "MyClient", out blnCreate);
//if (blnCreate)
CloseRunningInstance();
Application.Run(new MainFrm());
}
//Close the existed instance of my application
static void CloseRunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Close the other process instance.
process.Kill();
process.WaitForExit();
}
}
}
}
}
}
相关文章推荐
- 使用互斥量保证程序最多只有一个实例运行
- 保证Winform程序只有一个实例在运行
- 保证程序只有一个运行实例
- 使用互斥量保证程序最多只有一个实例运行
- WinForm程序,保证只有一个实例在运行(网上搜集的东西)
- 保证程序只有一个实例运行 &&& 动态调用DLL的研究
- 保证一个程序在同一台PC中只运行一个实例的两种方法
- 程序只有一个实例运行
- 程序只运行一个实例,并且把前一个激活
- VC保证应用程序只有一个实例在运行
- linux入手小程序——任何一个程序的运行只有借助于操作系统才能得以顺利完成的小实例
- 保证某一执行文件只有一个实例在运行
- 保证应用程序只有一个实例在运行
- 互斥对象(Mutex)、事件对象(Event) 与 关键代码段(CriticalSection) 的比较(互斥量Mutex 保证只有一个实例运行)
- Win32 程序 确保只有一个实例运行
- 保证一个程序只有一个应用程序在运行
- 利用互斥控制程序只有一个运行实例
- 让你的Java程序只有一个进程实例在运行
- 保证应用程序只有一个实例在运行
- 确保只有一个程序实例运行(C#)之解决方案