我试着这样做:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using DannyGeneral;
namespace mws
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
if (IsApplicationAlreadyRunning() == true)
{
MessageBox.Show("The application is already running");
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
catch (Exception err)
{
Logger.Write("error " + err.ToString());
}
}
static bool IsApplicationAlreadyRunning()
{
string proc = Process.GetCurrentProcess().ProcessName;
Process[] processes = Process.GetProcessesByName(proc);
if (processes.Length > 1)
{
return true;
}
else
{
return false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是我遇到了一些问题.
首先,当我在Visual Studio中加载项目然后运行我的程序时,它正在检测我的项目的vshost.exe文件,例如:My project.vshost
而且我希望只有在我运行程序时它才会检测我的程序是否正在运行,只有当它找到.exe例如:我的project.exe而不是vshost.
fla*_*ayn 17
看一下使用互斥锁.
static class Program {
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
static void Main() {
if(mutex.WaitOne(TimeSpan.Zero, true)) {
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
finally
{
mutex.ReleaseMutex();
}
} else {
MessageBox.Show("only one instance at a time");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们的应用程序正在运行,WaitOne将返回false,您将收到一个消息框.
正如@Damien_The_Unbeliever正确指出的那样,您应该为您编写的每个应用程序更改互斥锁的Guid!
资料来源:http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
| 归档时间: |
|
| 查看次数: |
9587 次 |
| 最近记录: |