DevExpress Winform使用单例运行程序方法和非DevExpress使用Mutex实现程序单实例运行且运行则激活窗体的方法

42 篇文章 15 订阅
12 篇文章 5 订阅

网上关于C#单例运行程序的方法都是比较简单,有些甚至是无法实现功能的,不知道他们试没试过就发帖,因为自己之前都是用第三方控件DevExpress,单例运行也是用它本身自带的一个方法,调用此方法需要引用DevExpress的DevExpress.DevAV.v17.1.Data.dll

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());
            }
}

以前懒,看到有现成的就拿现成的,也没去想具体如何实现,刚好有人问起,才决定去看看源码,发现DevExpress的这个方法原来是用了Mutex来实现的,整合了一下资料,重新写一个供C#桌面应用程序通用的单例运行方法,代码如下:

其中需要引用以下命名空间:

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;
                }
            }
        }
    }

调用的demo如下,亲测可以,若无法实现的请留言讨论(本文章是原创文章,转载请标明,盗版必究,觉得文章对你帮助的可以点个赞表示支持一下,谢谢):

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

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值