views:

338

answers:

2

I'm trying to make it so that when you double click the tray icon, my program will either a) minimize if it is in the normal state, or b) return to normal state if it is minimized.

I have the following code (where TrayIcon is a NotifyIcon control):

public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void TrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (MainForm.ActiveForm.WindowState == FormWindowState.Normal)
            {
                MainForm.ActiveForm.WindowState = FormWindowState.Minimized;
            }
            else
            {
                MainForm.ActiveForm.WindowState = FormWindowState.Normal;
            }
        }
    }

However, when i run the code and double click the icon, it gives me a NullReferenceException and says (on the 'if' line) that the Object Reference is not set to an instance of an object.

I'm not quite sure what to do.

+1  A: 

use 'this' instead of 'MainForm.ActiveForm'

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void TrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (this.WindowState == FormWindowState.Normal)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        else
        {
            this.WindowState = FormWindowState.Normal;
        }
    }
}
Manitra Andriamitondra
+3  A: 

If the form is in the Minimized state or if you click on anything on the taskbar, the form might lose focus thus becoming inactive ... thus ActiveForm will be null.

If TrayIcon is attached to the form and isn't a standalone control running in the background... then just use the "this" reference instead to refer the the related form.

if (this.WindowState == FormWindowState.Normal)
{
    this.WindowState = FormWindowState.Minimized;
}
else
{
    this.WindowState = FormWindowState.Normal;
}

You should not use ActiveForm when your code doesn't depends on the form being active.

chakrit
No actually, I'm just kind of a noobie when dealing with forms.
The.Anti.9