Mutex implemented using C # program running and running a single instance of the activation method of the form

Online concerning C # singleton method to run the program are relatively simple, some are even unable to realize the function, do not know they have not tried to test the post, because before their own are using third-party controls DevExpress, Singleton also use it to run itself comes with a method, this method is called the need to refer to DevExpress.DevAV.v17.1.Data.dll DevExpress

static void Main()
        {
var appName= Process.GetCurrentProcess().ProcessName;
using (DevExpress.Internal.DevAVDataDirectoryHelper.SingleInstanceApplicationGuard(appName, out exit))
            {
                if (exit)
                    return;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
}

Lazy before, see a ready-Take-shelf, but also did not think about how to achieve specific, just someone asked, before deciding to go look at the source and found DevExpress This method was originally used Mutex to achieve integration of a moment data, re-writing a C # desktop application for generic singleton method of operation, as follows:

Which you need to reference the following namespace:

using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
/// <summary>
    /// 单实例应用程序--by涛神
    /// </summary>
    public class SingleInstanceApplication
    {
        /// <summary>
        /// 判断应用是否运行
        /// </summary>
        /// <param name="processName"></param>
        /// <param name="exit"></param>
        /// <returns></returns>
        public static IDisposable Guard(out bool exit)
        {
            Process currentProcess = Process.GetCurrentProcess();
            var processName = currentProcess.ProcessName;
            Mutex mutex = new Mutex(true, processName, out bool createNew);
            if (createNew)
            {
                exit = false;
            }
            else
            {
                Process[] processesByName = Process.GetProcessesByName(currentProcess.ProcessName);
                int num = 0;
                while (num < (int)processesByName.Length)
                {
                    Process process = processesByName[num];
                    if (process.Id == currentProcess.Id || !(process.MainWindowHandle != IntPtr.Zero))
                    {
                        num++;
                    }
                    else
                    {
                        WinApiHelper.SetForegroundWindow(process.MainWindowHandle);
                        WinApiHelper.RestoreWindowAsync(process.MainWindowHandle);
                        break;
                    }
                }
                exit = true;
            }
            return mutex;
        }
        private static class WinApiHelper
        {
            [SecuritySafeCritical]
            public static bool IsMaxmimized(IntPtr hwnd)
            {
                WinApiHelper.Import.WINDOWPLACEMENT wINDOWPLACEMENT = new WinApiHelper.Import.WINDOWPLACEMENT();
                if (!WinApiHelper.Import.GetWindowPlacement(hwnd, ref wINDOWPLACEMENT))
                {
                    return false;
                }
                return wINDOWPLACEMENT.showCmd == WinApiHelper.Import.ShowWindowCommands.ShowMaximized;
            }

            [SecuritySafeCritical]
            public static bool RestoreWindowAsync(IntPtr hwnd)
            {
                return WinApiHelper.Import.ShowWindowAsync(hwnd, (WinApiHelper.IsMaxmimized(hwnd) ? 3 : 9));
            }

            [SecuritySafeCritical]
            public static bool SetForegroundWindow(IntPtr hwnd)
            {
                return WinApiHelper.Import.SetForegroundWindow(hwnd);
            }

            private static class Import
            {
                [DllImport("user32.dll", CharSet = CharSet.None, ExactSpelling = false)]
                public static extern bool GetWindowPlacement(IntPtr hWnd, ref WinApiHelper.Import.WINDOWPLACEMENT lpwndpl);

                [DllImport("user32.dll", CharSet = CharSet.None, ExactSpelling = false)]
                public static extern bool SetForegroundWindow(IntPtr hWnd);

                [DllImport("user32.dll", CharSet = CharSet.None, ExactSpelling = false)]
                public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

                public enum ShowWindowCommands
                {
                    Hide,
                    Normal,
                    ShowMinimized,
                    ShowMaximized,
                    ShowNoActivate,
                    Show,
                    Minimize,
                    ShowMinNoActive,
                    ShowNA,
                    Restore,
                    ShowDefault,
                    ForceMinimize
                }

                public struct WINDOWPLACEMENT
                {
                    public int length;

                    public int flags;

                    public WinApiHelper.Import.ShowWindowCommands showCmd;

                    public Point ptMinPosition;

                    public Point ptMaxPosition;

                    public Rectangle rcNormalPosition;
                }
            }
        }
    }

Call demo below, pro-test can not be achieved if the discussion, please leave a message ( this article is the original article, reproduced, please, pirated reserved, that article can help you point a praise support, thank you ):

static void Main()
        {
            using(SingleInstanceApplication.Guard(out bool exit))
            {
                if (exit)
                    return;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }

 

Guess you like

Origin blog.csdn.net/u012097590/article/details/92806194