C# winform 只运行一个应用程序
2018-01-15 22:25
134 查看
应用程序只有一个实例,当启动一次时创建实例,当多次启用时激活当前实例。
创建一个单利管理类
在Program.cs中添加如下代码
第二版的实现:
参考资料:https://www.codeproject.com/Articles/12890/Single-Instance-C-Application-for-NET-2-0
https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application
创建一个单利管理类
using Microsoft.VisualBasic.ApplicationServices; public class AppContainer : WindowsFormsApplicationBase { public AppContainer() { IsSingleInstance = true; EnableVisualStyles = true; ShutdownStyle = ShutdownMode.AfterMainFormCloses; } protected override void OnCreateMainForm() { MainForm = new Form1(); } }
在Program.cs中添加如下代码
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { AppContainer app = new AppContainer(); app.Run(Environment.GetCommandLineArgs()); } }
第二版的实现:
using System.Threading; using System.Runtime.InteropServices; static class Program { #region 第二版 static Mutex mutex = new Mutex(true, "{FFAB7D56-89DB-4059-8465-4EB852326633}"); #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { #region 第一版 //AppContainer app = new AppContainer(); //app.Run(Environment.GetCommandLineArgs()); #endregion #region 第二版 if (mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST,NativeMethods.WM_SHOW, IntPtr.Zero,IntPtr.Zero); } #endregion } } #region 第二版 internal class NativeMethods { public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOW = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message); } #endregion
public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region 第二版 protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_SHOW) { if (WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } bool top = TopMost; TopMost = true; TopMost = top; } base.WndProc(ref m); } #endregion }
参考资料:https://www.codeproject.com/Articles/12890/Single-Instance-C-Application-for-NET-2-0
https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application
相关文章推荐
- C# winform应用程序运行后,bin文件夹中会自动生成3个文件和一个应用程序
- 怎样才能在C#桌面应用程序(winform)中调用运行EXE文件?
- C# 只能运行一个winForm进程
- 转C# 只能运行一个winForm进程
- Winform(C#)限制程序只运行一个实例
- winform只允许一个应用程序运行
- 如何让应用程序仅运行一个实例(c#)
- C# 让应用程序只运行一个实例
- C# winform 只运行一个实例窗口
- c# Winform 如何实现程序只能同时运行一个实例
- C# .net防止一个程序(WinForm)重复运行的方法。
- C# .net防止一个程序(WinForm)重复运行的方法。
- c# winform 只允许运行一个实例
- 禁止一个应用程序的实例在同一台机器上运行多个(C#源码)
- winform只允许一个应用程序运行
- 如何让应用程序仅运行一个实例(c#)
- 保证C#应用程序只有一个实例在运行
- C#编写Windows桌面应用程序使程序同时只能运行一个副本
- C#应用程序只运行一个实例的代码
- C# 应用程序开发中,如何防止一个C#开发的EXE被多次运行