您的位置:首页 > 编程语言 > C#

C# 如何让窗体最小化到后台托管(类似QQ托管一样)

2012-07-20 21:50 465 查看
首先,向想要后台运行的 主窗体设计页面添加两个控件

notifyIcon 控件 和 contextMenuStrip控件

notifyIcon 控件 中的 Icon属性 增加图标 (这个图标就是你后台托管时显示的图标)

在 contextMenuStrip 属性中 增加 contextMenuStrip控件的名字 (主要让 托管的图标响应右键,显示右键菜单)

在 contextMenuStrip控件 中增加 让托管中显示的 右键菜单

接着,在主窗体的代码页面中 增加 this.SizeChanged +=new EventHandler(Form1_SizeChanged);

这个为响应窗体上 最大化,最小化,关闭 所触发的事件

事件为

[c-sharp] view
plaincopy

private void Form1_SizeChanged(object sender,EventArgs e)

{

if (this.WindowState == FormWindowState.Minimized)

{

this.Hide();//隐藏主窗体

this.notifyIcon1.Visible = true;//让notifyIcon1图标显示

}

}

在 notifyIcon控件 鼠标点击事件中 添加

[c-sharp] view
plaincopy

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) //当鼠标点击托管图标时触发

{

if (e.Button == MouseButtons.Left)//当鼠标点击为左键时

{

this.Show();//显示主窗体

this.WindowState = FormWindowState.Normal;//主窗体的大小为默认

}

}

在contextMenuStrip控件中 设定的 菜单中响应事件

[c-sharp] view
plaincopy

private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)//鼠标右击托管图标时触发的事件

{

this.Close();

}

这样就可以让你的窗体 在后台托管了

完整的代码如下:

[c-sharp] view
plaincopy

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace FormBackstageCustody

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

this.SizeChanged +=new EventHandler(Form1_SizeChanged);

}

private void Form1_SizeChanged(object sender,EventArgs e)

{

if (this.WindowState == FormWindowState.Minimized)

{

this.Hide();//隐藏主窗体

this.notifyIcon1.Visible = true;//让notifyIcon1图标显示

}

}

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) //当鼠标点击托管图标时触发

{

if (e.Button == MouseButtons.Left)//当鼠标点击为左键时

{

this.Show();//显示主窗体

this.WindowState = FormWindowState.Normal;//主窗体的大小为默认

}

}

private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)//鼠标右击托管图标时触发的事件

{

this.Close();

}

}

}

原文出处:http://blog.csdn.net/zhuimeng11025/article/details/6085312
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: