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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值