利用c#制作托盘程序,并禁止多个应用实例运行

托盘程序的制作:

1.把NotifyIcon控件拉一个到窗体上,并设置NotifyIcon的Icon(很重要!否则运行后看不到效果)
2.窗体关闭时,将程序最小化到系统托盘上

//开始运行时隐藏主窗体
private void Form1_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized; //初始为最小化状态
            this.ShowInTaskbar = false; //隐藏任务栏图标
        }
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());
            }

        }

    }

}
作者: 菩提树下的杨过
出处: http://yjmyzz.cnblogs.com 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值