C# WinForm 程序单实例运行,再次运行时激活前一个实例
2013-06-20 17:22
871 查看
一个简单的小程序,演示了winform程序如何运行单实例。当有实例运行时,再次单击,会激活第一个实例。
附主要源码:
Program.cs
Form1.cs
附源码下载地址:点击打开链接
附主要源码:
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading; namespace SingleInstance { static class Program { public static EventWaitHandle ProgramStarted; /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { // 尝试创建一个命名事件 bool createNew; ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyStartEvent", out createNew); // 如果该命名事件已经存在(存在有前一个运行实例),则发事件通知并退出 if (!createNew) { ProgramStarted.Set(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace SingleInstance { public partial class Form1 : Form { NotifyIcon notifyIcon1 = new NotifyIcon(); public Form1() { InitializeComponent(); this.notifyIcon1.Text = "Double click to show window"; this.notifyIcon1.Icon = System.Drawing.SystemIcons.Application; this.notifyIcon1.DoubleClick += OnNotifyIconDoubleClicked; this.SizeChanged += OnSizeChanged; ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false); this.WindowState = FormWindowState.Normal; } // 当最小化时,放到系统托盘。 void OnSizeChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.notifyIcon1.Visible = true; this.Visible = false; } } // 当双击托盘图标时,恢复窗口显示 void OnNotifyIconDoubleClicked(object sender, EventArgs e) { this.Visible = true; this.notifyIcon1.Visible = false; this.WindowState = FormWindowState.Normal; } // 当收到第二个进程的通知时,显示窗体 void OnProgramStarted(object state, bool timeout) { this.notifyIcon1.ShowBalloonTip(2000, "Hello", "I am here...", ToolTipIcon.Info); this.Show(); this.WindowState = FormWindowState.Normal; //注意:一定要在窗体显示后,再对属性进行设置 } } }
附源码下载地址:点击打开链接
相关文章推荐
- 【转】C# WinForm 程序单实例运行,再次运行时激活前一个实例
- C# WINFORM判断程序是否运行,且只能运行一个实例(转)
- C# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C#winform判断程序已经运,且只能运行一个实例
- 解决C# WINFORM程序只允许运行一个实例的几种方法详解
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- c# Winform 如何实现程序只能同时运行一个实例
- c#WinForm 程序单实例运行并打开前一个实例(Mutex+API)
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- 让程序中的某个Form某个时间只运行一个实例 [C#、WinForm]
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# WINFORM判断程序是否运行,且只能运行一个实例
- Winform(C#)限制程序只运行一个实例
- C#winform中只允许程序运行一个实例
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C#_WinForm程序只允许运行一个实例
- C# WINFORM判断程序是否运行,且只能运行一个实例
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# WINFORM判断程序是否运行,且只能运行一个实例
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.