一、通过系统事件

1、实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace Example
{
    public class SinglonProgram
    {

        #region 字段

        //显示的主窗体
        private Form mainForm;

        //线程同步事件
        private static EventWaitHandle programWaitHandle;

        #endregion

        #region 属性

        #endregion

        #region 构造函数

        public SinglonProgram(Form showForm)
        {
            this.mainForm = showForm;

            //注册一个等待WaitHandle的委托
            ThreadPool.RegisterWaitForSingleObject(programWaitHandle, (obj, timeOut) =>
            {
                ShowForm();
            },
            null, -1, false);

        }

        #endregion

        #region 私有函数  显示窗体、等

        /// <summary>
        /// 显示窗体
        /// </summary>
        private void ShowForm()
        {
            //在拥有mainForm窗体的线程上执行无参委托(Action)
            this.mainForm.Invoke(new Action(() =>
                {
                    this.mainForm.Visible = true;
                    if(this.mainForm.WindowState == FormWindowState.Minimized)
                    {
                        this.mainForm.WindowState = FormWindowState.Normal;
                    }
                    this.mainForm.Show();

                    bool isForeground = SetForegroundWindow(this.mainForm.Handle);
                    MessageBox.Show(isForeground.ToString());
                }
            ));
        }

        #endregion

        #region 公共函数  只有一个程序运行

        /// <summary>
        /// 是否创建了已命名的系统事件
        /// </summary>
        /// <returns></returns>
        public static bool isNamedSystemEvent()
        {
            bool createdNew;
            programWaitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, Application.ProductName, out createdNew);
            return !createdNew;
        }

        /// <summary>
        /// 确保只有一个程序运行
        /// </summary>
        public static void Confirm()
        {
            // 如果该命名事件已命名(运行实例已经存在),则发事件通知并退出
            if (isNamedSystemEvent())
            {
                programWaitHandle.Set();    //将事件状态设置为终止状态,允许一个或多个等待线程继续
                Environment.Exit(1);
            }
        }

        #endregion

        #region 接口函数 激活窗体且前端显示等

        /// <summary>
        /// 前端显示且激活窗体
        /// </summary>
        /// <param name="hWnd">窗体句柄</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);


        #endregion

        #region 虚函数

        #endregion
    }
}
View Code

相关文章:

  • 2022-02-01
  • 2021-06-25
  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-13
  • 2022-02-23
  • 2022-02-09
  • 2022-01-14
  • 2022-12-23
  • 2022-03-05
相关资源
相似解决方案