欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#实现托盘程序并禁止多个应用实例运行的方法

时间:2021-07-13 08:23:12|栏目:.NET代码|点击:

本文实例讲述了C#实现托盘程序并禁止多个应用实例运行的方法。分享给大家供大家参考,具体如下:

托盘程序的制作:

1.把NotifyIcon控件拉一个到窗体上,并设置NotifyIcon的Icon(很重要!否则运行后看不到效果)

2.窗体关闭时,将程序最小化到系统托盘上

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  //MessageBox.Show("程序将最小化到系统托盘区");
  e.Cancel = true; // 取消关闭窗体
  this.Hide();
  this.ShowInTaskbar = false;//取消窗体在任务栏的显示
  this.notifyIcon1.Visible = true;//显示托盘图标
}

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.左键单击托盘图标时,显示主窗体,右击时当然是弹出上面设置的菜单

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>
    /// 应用程序的主入口点。
    /// </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#程序设计有所帮助。

上一篇:NopCommerce架构分析之(三)EntityFramework数据库初试化及数据操作

栏    目:.NET代码

下一篇:基于C# 中可以new一个接口?的问题分析

本文标题:C#实现托盘程序并禁止多个应用实例运行的方法

本文地址:http://www.codeinn.net/misctech/156806.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有