NotifyIcon visible if exited from 2nd form

orbwave

Newcomer
Joined
Jun 3, 2005
Messages
3
I added another form to my system tray application and in that form the user can perform an action that requires the program to reload itself

Code:
// Alert the user that the application will restart
MessageBox.Show("Settings Saved. Click OK to restart the application", 
                         "Saved Settings", MessageBoxButtons.OK,
                         MessageBoxIcon.Stop);

// Shut down the current app instance
Application.Exit();

// Restart the app
System.Diagnostics.Process.Start(Application.ExecutablePath);

Problem is, I can't get the icon to disappear since the application is being exited from a form other than the main one that loaded the icon. If I exit the application from the main form, icon gets removed from the tray no problem.

How can I get rid of the icon when I exit the app from another form instance?
 
Why can't you close the main window?

MSDN said:
CAUTION The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.

Since Application.Exit appearently does not close forms in a normal fasion, it is not surprising that the NotiftyIcon is not properly taken care of.
 
I've tried that, but I can't figure out how to get a reference to the main form to call the Close() method.
 
What I generally do is use a static property like so:
Visual Basic:
Public Class Form1
    Static _Inst As Form1
 
    Public Sub New()
        'ADD this to the existing constructor code
        'Store a static reference to the main form
        _Inst = Me
    End Sub
 
    Public Shared ReadOnly Property AppInstance() As Form1
        Get
            'Return the main form
            Return _Inst
        End Get
    End Function
End Class
 
'To close the application:
Form1.AppInstance.Close()

Code:
public class Form1 : System.Windows.Forms.Form {
static Form1 _inst; 
		
	public Form1() {
		// ADD this to the constructor
		_inst = this;
	}
		
	public static Form1 AppInstance {
		get	{
			return _inst;
			Form1.AppInstance.Close();
		}
	}
}

// To close the app,
 
Last edited:
Back
Top