Winform 單一實例運行 — 新的呈現方式

來源:互聯網
上載者:User
討論見原帖(如何操作我的程式的另一個執行個體(進程)):
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);
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.