首页 文章

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

提问于
浏览
2

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

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

2 回答

  • 3

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

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

  • 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();
        }
    
      }
    

相关问题