如何在c#winform中只打开一个窗口
本文关键字:窗口 一个 c#winform | 更新日期: 2023-09-27 18:00:31
我写了一个c#windorm应用程序并生成了一个安装文件,当我完成安装时,每次双击桌面上的快捷方式,它都会打开一个新的窗口,有人能告诉我,当我双击桌面中的快捷方式时,我怎么能打开原来的窗口吗?
我更喜欢类似于下面的互斥解决方案。通过这种方式,如果已经加载,它会重新关注应用程序
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;
}
}
}
}
}
如果应用程序窗口已经在运行,它会将焦点放在应用程序窗口上。