classSingleInstanceController : WindowsFormsApplicationBase { publicSingleInstanceController() { // Make this a single-instance application this.IsSingleInstance = true; this.EnableVisualStyles = true;
// There are some other things available in the VB application model, for // instance the shutdown style: this.ShutdownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses;
// Add StartupNextInstance handler this.StartupNextInstance += new StartupNextInstanceEventHandler(this.SIApp_StartupNextInstance); }
///<summary> /// We are responsible for creating the application's main form in this override. ///</summary> protectedoverridevoidOnCreateMainForm() { // Instantiate your main application form // Create an instance of the main form and set it in the application; // but don't try to run it. this.MainForm = new Login();
// We want to pass along the command-line arguments to this first instance Random randNum = new Random(); }
///<summary> /// This is called for additional instances. The application model will call this /// function, and terminate the additional instance when this returns. ///</summary> ///<param name="eventArgs"></param> protectedvoidSIApp_StartupNextInstance(object sender, StartupNextInstanceEventArgs eventArgs) { // Here you get the control when any other instance is // invoked apart from the first one. // You have args here in e.CommandLine.
// You custom code which should be run on other instances
// Copy the arguments to a string array string[] args = newstring[eventArgs.CommandLine.Count]; eventArgs.CommandLine.CopyTo(args, 0);
// Create an argument array for the Invoke method object[] parameters = newobject[2]; parameters[0] = this.MainForm; parameters[1] = args;
// Need to use invoke to b/c this is being called from another thread. this.MainForm.Invoke(new Login.ProcessParametersDelegate(((Login)this.MainForm).ProcessParameters), parameters); } } }