当前位置:首页 > Windows程序 > 正文

C#:只运行一个程序

2021-03-26 Windows程序

一、通过系统事件

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>窗体句柄</param> /// <returns></returns> [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); #endregion #region 虚函数 #endregion } }

View Code

2、调用如下:

static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { SinglonProgram.Confirm(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } }

View Code

二、通过查询线程

具体如下:(测试时发现,不调试和调试区别下会产生两个程序)

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68061.html