雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

C#實現(xiàn)托盤程序并禁止多個應(yīng)用實例運行的方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊:

本文實例講述了C#實現(xiàn)托盤程序并禁止多個應(yīng)用實例運行的方法。分享給大家供大家參考,具體如下:

托盤程序的制作:

1.把NotifyIcon控件拉一個到窗體上,并設(shè)置NotifyIcon的Icon(很重要!否則運行后看不到效果)

2.窗體關(guān)閉時,將程序最小化到系統(tǒng)托盤上

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  //MessageBox.Show("程序?qū)⒆钚』较到y(tǒng)托盤區(qū)");
  e.Cancel = true; // 取消關(guān)閉窗體
  this.Hide();
  this.ShowInTaskbar = false;//取消窗體在任務(wù)欄的顯示
  this.notifyIcon1.Visible = true;//顯示托盤圖標(biāo)
}

3.放一個上下文菜單,添加幾個基本項,"顯示主窗體","退出" ,將這個菜單掛到NotifyIcon上

private void menuShow_Click(object sender, EventArgs e)
{
  this.Show();
  this.ShowInTaskbar = true;
  this.notifyIcon1.Visible = false;
}
private void menuExit_Click(object sender, EventArgs e)
{
  this.Dispose(true);
  Application.ExitThread();
}

4.左鍵單擊托盤圖標(biāo)時,顯示主窗體,右擊時當(dāng)然是彈出上面設(shè)置的菜單

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
    this.Show();
    this.ShowInTaskbar = true;
    this.notifyIcon1.Visible = false;
  }
}

防止這個程序同時運行多個

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
namespace LuceneTest
{
  static class Program
  {
    /// <summary>
    /// 應(yīng)用程序的主入口點。
    /// </summary>
    [STAThread]
    static void Main()
    {
      bool bCreatedNew;
      Mutex m = new Mutex(false, "Product_Index_Cntvs", out bCreatedNew);
      if (bCreatedNew)
      {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
      }
    }
  }
}

希望本文所述對大家C#程序設(shè)計有所幫助。

上一篇:輕松學(xué)習(xí)C#的正則表達(dá)式

欄    目:C#教程

下一篇:輕松學(xué)習(xí)C#的密封類

本文標(biāo)題:C#實現(xiàn)托盤程序并禁止多個應(yīng)用實例運行的方法

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6824.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有