Winforms - 为什么系统托盘双击后的“显示()”最终会在我的应用程序中最小化?

时间:2010-04-04 20:30:25

标签: winforms show notifyicon

Winforms - 为什么系统托盘双击最终在我的应用程序中最小化后显示“Show()”?

如何确保在我的隐藏主表单恢复正常,未最小化(也未最大化)的notifyicon双击事件中

2 个答案:

答案 0 :(得分:3)

我猜你会把你的应用程序放在托盘中以减少操作。在这种情况下,Show只会恢复可见性。

尝试在Show()之前添加form.WindowState = Normal

答案 1 :(得分:1)

通常需要使用NotifyIcon隐藏您的表单,以便您的应用程序立即从托盘中启动。您可以通过覆盖SetVisibleCore()方法来防止它变得可见。您通常还希望在用户单击X按钮时阻止它关闭,重写OnFormClosing方法以隐藏表单。您需要一个上下文菜单,以允许用户真正退出您的应用。

将NotifyIcon和ContextMenuStrip添加到表单中。为CMS提供“显示”和“退出”菜单命令。使表单代码如下所示:

  public partial class Form1 : Form {
    bool mAllowClose;
    public Form1() {
      InitializeComponent();
      notifyIcon1.DoubleClick += notifyIcon1_DoubleClick;
      notifyIcon1.ContextMenuStrip = contextMenuStrip1;
      showToolStripMenuItem.Click += notifyIcon1_DoubleClick;
      exitToolStripMenuItem.Click += (o, e) => { mAllowClose = true; Close(); };
    }

    protected override void SetVisibleCore(bool value) {
      // Prevent form getting visible when started
      // Beware that the Load event won't run until it becomes visible
      if (!this.IsHandleCreated) {
        this.CreateHandle();
        value = false;
      }
      base.SetVisibleCore(value);
    }

    protected override void OnFormClosing(FormClosingEventArgs e) {
      if (!this.mAllowClose) {    // Just hide, unless the user used the ContextMenuStrip
        e.Cancel = true;
        this.Hide();
      }
    }

    void notifyIcon1_DoubleClick(object sender, EventArgs e) {
      this.WindowState = FormWindowState.Normal;  // Just in case...
      this.Show();
    }

  }
相关问题