如何检查是否该应用程序的另一实例正在运行应用程序、实例、正在运行

2023-09-02 11:56:25 作者:五个字微信男生

可能显示的文件:   What是创建一个单实例应用程序的正确方法?   Return当用户试图打开一个新的实例一个已经打开的应用程序

Possible Duplicates: What is the correct way to create a single instance application? Return to an already open application when a user tries to open a new instance

有人能证明它是如何可以检查程序的另一个实例(如:test.exe的)是否正在运行,如果是停止加载应用程序,如果有它的一个现有实例。

Could someone show how it is possible to check whether another instance of the program (e.g. test.exe) is running and if so stop the application from loading if there is an existing instance of it.

推荐答案

想一些严重的code?这里是。

Want some serious code? Here it is.

var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;

这适用于任何应用程序(任何名称),将成为如果有另一个实例同一应用程序。

This works for any application (any name) and will become true if there is another instance running of the same application.

编辑:要解决你的需求,你可以使用以下两种:

To fix your needs you can use either of these:

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;

这是你的主要方法,退出方法...或

from your Main method to quit the method... OR

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();

这将立即杀死当前所加载的过程。

which will kill the currently loading process instantly.

您需要添加一个引用的 System.Core.dll的的的的 .Count之间() 的扩展方法的。另外,您也可以使用 .Length 属性。

You need to add a reference to System.Core.dll for the .Count() extension method. Alternatively, you can use the .Length property.