C#/WPF 只允许一个实例程序运行并将已运行程序置顶

发布时间:2023年12月28日

使用用互斥量(System.Threading.Mutex):
?? ?同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。

实例代码:

    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll ")]
        //设置窗体置顶
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static Mutex _m = null;
        private static string currentProcess = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
        /// <summary>
        /// 只允许运行一个实例
        /// </summary>
        /// <param name="mutexName"></param>
        /// <returns>true:已经存在实例 false:不存在实例</returns>
        public static bool CheckRunOneInstance(string mutexName = null)
        {

            bool result = false;
            bool mutexWasCreated = false;
            try
            {
                bool requestInitialOwnership = true;
                if (mutexName == null)
                    mutexName = currentProcess;
                _m = new Mutex(requestInitialOwnership, mutexName, out mutexWasCreated);
                if (!mutexWasCreated)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 有程序运行,设置焦点
        /// </summary>
        private void Focus()
        {
            foreach (Process process in Process.GetProcesses())
            {
                try
                {
                    if (process.ProcessName.ToLower() != currentProcess.ToLower())
                        continue;
                    IntPtr hwnd = process.MainWindowHandle;
                    if (hwnd != IntPtr.Zero)
                    {
                        SetForegroundWindow(hwnd);
                        ShowWindow(hwnd, 2);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if(CheckRunOneInstance())
            {
                Focus();
                System.Windows.Application.Current.Shutdown();
                return;
            }
            else
            {
                new MainWindow().Show();
            }
        }
    }

实例链接:

https://download.csdn.net/download/lvxingzhe3/88668552

文章来源:https://blog.csdn.net/lvxingzhe3/article/details/135241287
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。