C# winform 只运行一个应用程序

应用程序只有一个实例,当启动一次时创建实例,当多次启用时激活当前实例。 

创建一个单利管理类

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

原文地址:https://www.cnblogs.com/godbell/p/8261717.html