Winform 单实例运行 -- 新的呈现方式

   
讨论见原帖(如何操作我的程序的另一个实例(进程)):
http://topic.csdn.net/u/20081221/01/457bb3b1-2f19-47e2-9621-cf4117ee45ce.html

       
using System;
using System.Threading;
using System.Windows.Forms;

static class Program
{
public static EventWaitHandle ProgramStarted;

[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());
}
}



C# code

// Form1.cs
//
using System;
using System.Windows.Forms;
using System.Threading;

public partial class Form1 : Form
{
NotifyIcon notifyIcon1
= new NotifyIcon();

public Form1()
{
// InitializeComponent();
this .notifyIcon1.Text = " Double click me to show window " ;
this .notifyIcon1.Icon = System.Drawing.SystemIcons.Information;
this .notifyIcon1.DoubleClick += OnNotifyIconDoubleClicked;
this .SizeChanged += OnSizeChanged;
ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted,
null , - 1 , false );
}

// 当最小化时,放到系统托盘。
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);
}
}

你可能感兴趣的:(WinForm)