/// <summary> /// 构造函数 /// </summary> public FrmMain() { if (this.TryCheckSingleton()){ Environment.Exit(0); } } //单一线程同步事件 private EventWaitHandle ewhSingleton; //保存CMIS Windows 消息编号 private int WM_CMISSTARTED; #region 单一客户端实例 /// <summary> /// 验证单一线程 /// </summary> /// <returns></returns> private bool TryCheckSingleton(){ try{ this.WM_CMISSTARTED = (int)RegisterWindowMessage("CmisStarted"); bool flag; this.ewhSingleton = new EventWaitHandle(false, EventResetMode.AutoReset, "CmisInstance", out flag); if (!flag){ PostMessage((IntPtr)0xffff, this.WM_CMISSTARTED, 0, 0); } return !flag; }catch (Exception){ return false; } } /// <summary> /// 激活主窗口 /// </summary> private void ActiveMainWindow() { base.Activate(); BringWindowToTop(base.Handle); } /// <summary> /// 获得 Windows 消息 /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { if (m.Msg == this.WM_CMISSTARTED){ this.ActiveMainWindow(); return; } base.WndProc(ref m); } #region Windows API 声明 /// <summary> /// 注册Windows消息 /// </summary> /// <param name="lpString">注册消息的名字</param> /// <returns>消息编号</returns> [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern uint RegisterWindowMessage(string lpString); /// <summary> /// 该函数将一个消息放入(寄送)到与指定窗口创建的线程相联系消息队列里 /// </summary> /// <param name="hWnd">接收消息的窗口句柄</param> /// <param name="Msg">被寄送的消息</param> /// <param name="wParam">附加的消息特定的信息</param> /// <param name="lParam">附加的消息特定的信息</param> /// <returns>函数调用成功,返回非零值;如果函数调用失败,返回值是零</returns> [DllImport("user32.dll")] public static extern int PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam); /// <summary> /// 该函数将指定的窗口设置到Z序的顶部 /// </summary> /// <param name="hWnd">窗口句柄</param> /// <returns>如果函数成功,返回值为非零;如果函数失败,返回值为零</returns> [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd); #endregion #endregion