Ver*_*cas 117
想要一些严肃的代码?这里是.
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
Run Code Online (Sandbox Code Playgroud)
这适用于任何应用程序(任何名称),true
如果有另一个实例运行相同的应用程序,它将成为.
编辑:为了满足您的需求,您可以使用以下任一方法:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
Run Code Online (Sandbox Code Playgroud)
从您的Main方法退出方法...或
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
Run Code Online (Sandbox Code Playgroud)
这将立即杀死当前加载的进程.
您需要为扩展方法添加对System.Core.dll的引用.或者,您也可以使用酒店..Count()
.Length
Pat*_*son 55
它不确定你对"程序"的意思,但是如果你想将你的应用程序限制在一个实例上,那么你可以使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*thJ 13
这是一些很好的示例应用程序.以下是一种可能的方法.
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.MainModule.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.
}
Run Code Online (Sandbox Code Playgroud)
许多其他可能的方式.请参阅示例以了解替代方案
编辑1:刚刚看到你的评论,你有一个控制台应用程序.这在第二个样本中讨论.
归档时间: |
|
查看次数: |
108696 次 |
最近记录: |