托盘程序(WinForm)

1、托盘显示的标题、内容、图标等信息在界面设置。

2、后台代码

    public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.Visible == true)
{
e.Cancel = true;
this.Visible = false;
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Visible = false;
Application.Exit();
}
}


修改Program.cs

static class Program
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll ")]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
public static IntPtr formhwnd;

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

bool createdNew;
Mutex mutex = new Mutex(false, "Notify", out createdNew);
if (!createdNew)
{
Process instance;
Process currentProcess = Process.GetCurrentProcess();
Process[] process = Process.GetProcessesByName(currentProcess.ProcessName);
for (int i = 0; i < process.Length; i++)
{
if (process[i].Id != currentProcess.Id)
{
instance = process[i];
if (instance.MainWindowHandle != IntPtr.Zero)
{
SwitchToThisWindow(instance.MainWindowHandle, true);
}
else
{
formhwnd = FindWindow(null, "Form1");
ShowWindowAsync(formhwnd, 1);
SetForegroundWindow(formhwnd);
}
return;
}
}
}
Form1 form = new Form1();
Application.Run(form);
}
}

 

转载于:https://www.cnblogs.com/zhaoyanzhe/archive/2011/12/29/2305748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值