我如何隐藏一个窗口窗体时,点击x和关闭通过系统托盘ToolStripMenuItem
本文关键字:ToolStripMenuItem 系统 点击 隐藏 何隐藏 窗体 窗口 一个 | 更新日期: 2023-09-27 18:13:18
我是c# .Net的新手,我正在寻找一种方法来隐藏我的窗体窗口,当窗口上的'X'(右上角的关闭按钮)被点击,当我从我的系统托盘上下文菜单中单击退出时关闭应用程序
为了简化我想做的是我想要像Skype这样的东西,它可以通过系统托盘选项退出,并在点击窗口的交叉时隐藏到系统尝试以下是我的代码,我已经尝试在窗体关闭事件上重写cancel属性为true,但它也会停止系统尝试选项的关闭过程,我如何区分它们。
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Icon ico;
private void Form1_Load(object sender, EventArgs e)
{
ico = notifyIcon1.Icon;
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
}
private void showFormToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Show();
}
private void quitFormToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("{0} = {1}", "CloseReason", e.CloseReason);
messageBoxCS.AppendLine();
messageBoxCS.AppendFormat("{0} = {1}", "Cancel", e.Cancel);
messageBoxCS.AppendLine();
MessageBox.Show(messageBoxCS.ToString(), "FormClosing Event");
}
}
}
`
通常当我必须这样做时,我保留一个statusflag来记住来自其他地方的呼叫来关闭我。然后在结束处理程序中,我可以检查是否需要关闭或隐藏。
bool bFormCloseRequested = false: //member of my Form
void MyCloseClick_Handler{object sender, eventArgs e)
{
if(!bFormCloseRequested)
{
e.Cancel = true;
this.hide();
}
}