0

I can pass arguments into my application on startup, which works great! I can also stop multiple instances of the application from running which is great. However I'm trying to pass an argument into the application, but if the app is already running then run a method on the existing winform, instead of trying to open a new instance. I've tried using application.openforms and it doesnt appear to work for me.

I've tried using code similar to this:

if (System.Windows.Forms.Application.OpenForms["MainMenu"] != null)
    {
        (System.Windows.Forms.Application.OpenForms["MainMenu"] as Form1).Output();
    }

Program.cs

static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                MessageBox.Show("BorisCRM is already running. Only one instance of this application is allowed");
            }
            else
            {
                if (args.Length > 0)
                    Application.Run(new Forms.MainMenu(args[0]));
                else
                    Application.Run(new Forms.MainMenu("NoArg"));
            }
        }

MainMenu Form:

        if (s != "NoArg")
        {
            NewForm frm = new NewForm(getclient);
            frm.MdiParent = this;
            frm.Show();
        }

THIS WORKS.... open application - opens menu form, where i can choose menu items that open forms using the menu as its mdiparent.

THIS WORKS.... open application with argument - opens the menu form, and automatically opens another form using the menu as the parent mdi.

THIS DOESNT WORK... open application with argument (when the application is already running) - existing menu form automatically opens another form using the menu as the parent mdi.

  • You need to utilize some for of cross process comunication. Shared memory/ named pipe etc. First instance of application will listen for commands from other instances. – Jan Oct 15 '19 at 07:54
  • Take a look at [Mutex class](https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8). – Alessandro D'Andria Oct 15 '19 at 07:57
  • Possible duplicate of [What is the correct way to create a single-instance WPF application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application) – Alessandro D'Andria Oct 15 '19 at 08:01
  • your logic is a chaos, im wandering which type of application are you writing... – Erwin Draconis Oct 15 '19 at 08:08

1 Answers1

0

Mutex is the one!!! Thanks Alessandro D'Andria

I used this example: http://sanity-free.org/143/csharp_dotnet_single_instance_application.html