views:

100

answers:

2

Hi

Winforms - why does a "Show()" after a system tray double click end up in my app minimized?

How do I ensure Inthe notifyicon double click event that my hidden main form comes back visible as normal, not minimized (nor maximised for that matter too)

+2  A: 

I would guess that you put your application in tray on minimize action. In that case, Show just restores visibility.

Try adding form.WindowState = Normal before Show().

Josip Medved
+1 for making me go back and notice that my code to do this was flashing because I had the `Show()` *before* the `form.WindowState = Normal`.
ChrisF
Just tried this but could only get tis to work by putting it after the Show()
Greg
+1  A: 

Hiding your form with the NotifyIcon is often desirable so your app starts in the tray right away. You can prevent it from getting visible by overriding the SetVisibleCore() method. You also typically want to prevent it from closing when the user clicks the X button, override the OnFormClosing method to hide the form. You'll want a context menu to allow the user to really quit your app.

Add a NotifyIcon and a ContextMenuStrip to your form. Give the CMS the Show and Exit menu commands. Make the form code look like this:

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

  }
Hans Passant
Thanks, I'll use this
Greg