0

I have a simple winform program, that has 1 textbox. I want to hide it, if it loses focus (using Form1_Deactivate event for that) or user hits enter (then it also open up chrome with specific query) and show it's icon in the tray. After double-clicking tray icon I want to show the form again and give it focus. It works for the first two times (literally). Form shows, hides, shows, hides and next time it shows it doesn't have focus and also NullReferenceException related to NotifyIcon is being thrown.

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

    private void txtSlowo_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
        {
            Process.Start("chrome.exe", @"http:\\www.sjp.pl\" + txtSlowo.Text);

            txtSlowo.Text = "";
            this.notifyIcon1.Visible = true;
            this.Visible = false;
            e.Handled = true;
        }
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        this.notifyIcon1.Visible = false;
        this.Show();
        txtSlowo.Text = "";
    }

    private void Form1_Deactivate(object sender, EventArgs e)
    {
        this.Hide();
        this.notifyIcon1.Visible = true; //this line throws the exception
    }
}

Github in case you want to see whole project

EDIT: I'm assuming this is the stacktrace of the exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Forms.NotifyIcon.UpdateIcon(Boolean showIconInTray)
   at System.Windows.Forms.NotifyIcon.set_Visible(Boolean value)
   at SJPCheck.Form1.Form1_Deactivate(Object sender, EventArgs e) in c:\users\jan\documents\visual studio 2015\Projects\SJPCheck\SJPCheck\Form1.cs:line 42
   at System.Windows.Forms.Form.OnDeactivate(EventArgs e)
   at System.Windows.Forms.Form.set_Active(Boolean value)
   at System.Windows.Forms.Form.WmActivate(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
JanRad
  • 327
  • 2
  • 12

0 Answers0