gpt4 book ai didi

c# - 如何运行一个 c# WinForm 应用程序实例?

转载 作者:太空狗 更新时间:2023-10-30 01:23:02 27 4
gpt4 key购买 nike

我有一个 C# 应用程序,它在启动时显示登录表单,并在用户通过身份验证后显示主表单。我使用 Mutex 来限制我的应用程序只运行一个实例。而且,这仅适用于登录表单。显示主窗体后,它不会限制用户重新打开登录窗体。我一直在寻找一种解决方案,一旦主窗体已经打开,登录屏幕就无法显示。

这是我的 Program.cs

 [STAThread]
static void Main()
{
bool mutexCreated=true;

using (Mutex mutex = new Mutex(true, "eCS", out mutexCreated))
{
if (mutexCreated)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
XtraMessageBox.Show("Another instance of eCS is already running.", "eCS already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}

最佳答案

我做了一些小改动:


namespace CSMutex
{
static class Program
{
[STAThread]
static void Main()
{
bool mutexCreated=true;
using(Mutex mutex = new Mutex(true, "eCS", out mutexCreated))
{
if (mutexCreated)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login loging = new Login();
Application.Run(loging);
Application.Run(new Main() { UserName = loging.UserName });
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
MessageBox.Show("Another instance of eCS is already running.", "eCS already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
//SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
}
}

这按预期工作 - 即即使 Login 表单关闭(并且主应用程序表单已启动),它也不会让用户再次运行该应用程序。我决定不从 Login 中创建 Main(我相信你的应用程序是这样工作的)而是将参数传递给 Main .我还对 Login 做了一些小改动,使其具有 UserName 属性(与 Main 相同)。

关于c# - 如何运行一个 c# WinForm 应用程序实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12340043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com