如何强制 C# .net 应用程序在 Windows 中仅运行一个实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/184084/
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 to force C# .net app to run only one instance in Windows?
提问by jinsungy
Possible Duplicate:
What is the correct way to create a single instance application?
可能的重复:
创建单实例应用程序的正确方法是什么?
How to force C# .net app to run only one instance in Windows?
如何强制 C# .net 应用程序在 Windows 中仅运行一个实例?
回答by Mitchel Sellers
I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded
我更喜欢类似于以下的互斥锁解决方案。通过这种方式,如果应用程序已经加载,它会重新关注应用程序
using System.Threading;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
回答by Martin Plante
This is what I use in my application:
这是我在我的应用程序中使用的:
static void Main()
{
bool mutexCreated = false;
System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated )
{
if( MessageBox.Show(
"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
"slimKEYS already running",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question ) != DialogResult.Yes )
{
mutex.Close();
return;
}
}
// The usual stuff with Application.Run()
mutex.Close();
}
回答by snir
to force running only one instace of a program in .net (C#) use this code in program.cs file:
要强制在 .net (C#) 中仅运行一个程序的一个实例,请在 program.cs 文件中使用以下代码:
public static Process PriorProcess()
// Returns a System.Diagnostics.Process pointing to
// a pre-existing process with the same name as the
// current one, if any; or null if the current process
// is unique.
{
Process curr = Process.GetCurrentProcess();
Process[] procs = Process.GetProcessesByName(curr.ProcessName);
foreach (Process p in procs)
{
if ((p.Id != curr.Id) &&
(p.MainModule.FileName == curr.MainModule.FileName))
return p;
}
return null;
}
and the folowing:
以及以下内容:
[STAThread]
static void Main()
{
if (PriorProcess() != null)
{
MessageBox.Show("Another instance of the app is already running.");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
}
回答by Thyrador
another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:
单实例应用程序的另一种方法是检查它们的哈希和。在弄乱互斥锁(没有按我想要的方式工作)之后,我以这种方式工作:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Main()
{
InitializeComponent();
Process current = Process.GetCurrentProcess();
string currentmd5 = md5hash(current.MainModule.FileName);
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (process.Id != current.Id)
{
try
{
if (currentmd5 == md5hash(process.MainModule.FileName))
{
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
}
}
catch (/* your exception */) { /* your exception goes here */ }
}
}
}
private string md5hash(string file)
{
string check;
using (FileStream FileCheck = File.OpenRead(file))
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5Hash = md5.ComputeHash(FileCheck);
check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
}
return check;
}
it checks only md5 sums by process id.
它仅通过进程 ID 检查 md5 总和。
if an instance of this application was found, it focuses the running application and exit itself.
如果找到此应用程序的实例,它会聚焦正在运行的应用程序并自行退出。
you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.
您可以重命名它或对文件执行任何操作。如果 md5 哈希相同,它不会打开两次。
may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.
有人可以对此提出建议吗?我知道它得到了回答,但也许有人正在寻找互斥锁的替代方案。