C# WinForm 程序单实例运行,再次运行时激活前一个实例

时间:2023-02-20 23:09:04

一个简单的小程序,演示了winform程序如何运行单实例。当有实例运行时,再次单击,会激活第一个实例。

附主要源码:

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; //注意:一定要在窗体显示后,再对属性进行设置
}
}
}

附源码下载地址: 点击打开链接