可能重复:
什么是创build单个实例应用程序的正确方法?
有人可以显示如何可以检查另一个程序实例(如test.exe)是否正在运行,如果是这样,停止应用程序加载,如果有一个现有的实例。
访问冲突绘画ToolStripComboBox与XP Pro上的Webbrowser控件
可以加载网站更新的.NET桌面应用程序的安装程序是否存在?
C#WinForms托盘应用程序 – 不捕获Windows关机事件
如何通过Windows应用程序或Web应用程序调用代码来识别代码
从C#/ WPF应用程序重新启动机器
想要一些严肃的代码? 这里是。
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
这适用于任何应用程序(任何名称),并且如果有另一个 同一应用程序运行的实例,则会变为true 。
编辑:要解决您的需求,您可以使用这些:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
这将立即终止当前的加载过程。
您需要为.Count() 扩展方法添加对System.Core.dll的引用。 或者,您可以使用.Length属性。
不确定你的程序是什么意思,但是如果你想限制你的应用程序到一个实例,那么你可以使用一个Mutex来确保你的应用程序还没有运行。
[STAThread] static void Main() { Mutex mutex = new System.Threading.Mutex(false,"MyUniqueMutexName"); try { if (mutex.WaitOne(0,false)) { // Run the application Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { MessageBox.Show("An instance of the application is already running."); } } finally { if (mutex != null) { mutex.Close(); mutex = null; } } }
这是一些很好的示例应用程序。 以下是一种可能的方法。
public static Process RunningInstance() { 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.Mainmodulee.FileName) { //Return the other process instance. return process; } } } //No other instance was found,return null. return null; } if (MainForm.RunningInstance() != null) { MessageBox.Show("Duplicate Instance"); //Todo: //Your application logic for duplicate //instances would go here. }
许多其他可能的方式。 看到替代的例子。
第一。
第二个。
第三个
编辑1:刚才看到你的评论,你有一个控制台应用程序。 这在第二个示例中讨论。
Process静态类有一个方法GetProcessesByName(),您可以使用它来搜索正在运行的进程。 只要搜索具有相同可执行文件名的其他进程即可。
你可以试试这个
Process[] processes = Process.GetProcessesByName("processname"); foreach (Process p in processes) { IntPtr pFoundWindow = p.MainWindowHandle; // Do something with the handle... // }
尝试查看此实例识别应用程序的codeplex项目 。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。