C# 如何防止多次启动我的应用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15115241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent launching my app multiple times?
提问by Tolga Evcimen
I deployed my C# WinForms application using ClickOnce installation. Everything works fine with it (after a lot of work) :), but now I'm facing a problem:
我使用 ClickOnce 安装部署了我的 C# WinForms 应用程序。一切正常(经过大量工作):),但现在我面临一个问题:
Whenever I click on the application shortcut in the Start menu, a new instance starts. I need to avoid this.
每当我单击“开始”菜单中的应用程序快捷方式时,就会启动一个新实例。我需要避免这种情况。
What can I do to prevent multiple launches?
我能做些什么来防止多次启动?
采纳答案by semao
At program startup check if same process is already running:
在程序启动时检查相同的进程是否已经在运行:
using System.Diagnostics;
static void Main(string[] args)
{
String thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
}
回答by MikroDel
Use this code:
使用此代码:
[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(false, "Global\" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}
Application.Run(new Form1());
}
}
来自被误解的互斥锁
回答by bash.d
When starting you application, main always calls Application.Run()
. Look in your STAThread-Main method and before Application.Run
test, if there are running instances of your .exe.
启动应用程序时, main 始终调用Application.Run()
. 查看您的 STAThread-Main 方法并在Application.Run
测试之前,是否有您的 .exe 正在运行的实例。
Process p = Process.GetProcesses();
//check for your .exe
See thispost here.
在这里看到这个帖子。
回答by rusev
There is really good topic on that matter. You can find it here: using Mutext.
关于这个问题有一个很好的话题。你可以在这里找到它:使用 Mutext。
回答by user3195836
Using Mutex
is the way to go because guessing process names is full of flaws and niggles. Check out this really nice illustration
使用Mutex
是要走的路,因为猜测进程名称充满缺陷和琐事。看看这个非常好的插图
回答by Israel Ocbina
There are times **Mutex**
is not working in some areas. Like using in console application. So I tried using WMI Query.
有时**Mutex**
在某些领域不起作用。就像在控制台应用程序中使用一样。所以我尝试使用WMI Query。
Try this and it will work.
试试这个,它会起作用。
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!isStillRunning())
{
Application.Run(new Form1());
}
else {
MessageBox.Show("Previous process still running.",
"Application Halted", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Application.Exit();
}
}
//***Uses WMI Query
static bool isStillRunning() {
string processName = Process.GetCurrentProcess().MainModule.ModuleName;
ManagementObjectSearcher mos = new ManagementObjectSearcher();
mos.Query.QueryString = @"SELECT * FROM Win32_Process WHERE Name = '" + processName + @"'";
if (mos.Get().Count > 1)
{
return true;
}
else
return false;
}
Hope it helps.
希望能帮助到你。
回答by Serkan Polat
what i always using is
我一直使用的是
bool checkSingleInstance()
{
string procName = Process.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes = Process.GetProcessesByName(procName);
if (processes.Length > 1)
{
return true;
}
else
{
return false;
}
}
回答by saeed rajayi
solution in Windows form application Prohibit again run application(reopen application).
Windows 窗体应用程序中的解决方法 禁止再次运行应用程序(重新打开应用程序)。
1- first add Class RunAlready.cs
1-首先添加类 RunAlready.cs
2-Call method processIsRunning() with Name Process from RunAlready.cs in Program.cs
2-从 Program.cs 中的 RunAlready.cs 使用名称 Process 调用方法 processIsRunning()
Program.cs:
程序.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tirage.MainStand
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
PublicClass.Class.RunAlready RunAPP = new PublicClass.Class.RunAlready();
string outApp = RunAPP.processIsRunning("Tirage.MainStand");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainStand_FrmLogin fLogin = new MainStand_FrmLogin();
if (outApp.Length == 0)
{
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainStand_masterFrm());
}
}
else MessageBox.Show( "Instance already running");
}
}
}
class RunAlready:
类 RunAlready:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PublicClass.Class
{
public class RunAlready
{
public string processIsRunning(string process)
{
string xdescription = "";
System.Diagnostics.Process[] processes =
System.Diagnostics.Process.GetProcessesByName(process);
foreach (System.Diagnostics.Process proc in processes)
{
var iddd = System.Diagnostics.Process.GetCurrentProcess().Id;
if (proc.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
{
xdescription = "Application Run At time:" + proc.StartTime.ToString() + System.Environment.NewLine;
xdescription += "Current physical memory : " + proc.WorkingSet64.ToString() + System.Environment.NewLine;
xdescription += "Total processor time : " + proc.TotalProcessorTime.ToString() + System.Environment.NewLine;
xdescription += "Virtual memory size : " + proc.VirtualMemorySize64.ToString() + System.Environment.NewLine;
}
}
return xdescription;
}
}
}
回答by LovExpert
if (Process.GetProcesses().Count(p => p.ProcessName == "exe name") > 1)
{
foreach (var process in
Process.GetProcessesByName("exe name"))
{
process.Kill();
}
}
回答by DKH
In WPF, you can use this code in your App.xaml.cs
file:
在 WPF 中,您可以在App.xaml.cs
文件中使用以下代码:
private static System.Threading.Mutex _mutex = null;
protected override void OnStartup(StartupEventArgs e)
{
string mutexId = ((System.Runtime.InteropServices.GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false).GetValue(0)).Value.ToString();
_mutex = new System.Threading.Mutex(true, mutexId, out bool createdNew);
if (!createdNew) Current.Shutdown();
else Exit += CloseMutexHandler;
base.OnStartup(e);
}
protected virtual void CloseMutexHandler(object sender, EventArgs e)
{
_mutex?.Close();
}