4

in my application I've registered a file type (.asm) with my application (it's a tabbed notepad application), and when those files are double-clicked they open with my application through the arguments passed when it's loaded:

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

Now the problem is, while this does work, if one instance of my application is already running, whenever a file is opened, a new instance of it is created rather than a new tab being opened in the current instance which I don't want. So I thought of checking if the program is already running, and if it is then I would call a separate function in the main form to load that document instead. But the problem is, I don't know how you call a function in Main.cs from Program.cs, how do we do that?

dsolimano
  • 8,870
  • 3
  • 48
  • 63
Iceyoshi
  • 623
  • 3
  • 10
  • 14

2 Answers2

2

It's more complicated than just calling a function in Main.cs from Program.cs because the OS will launch a second process for you at the time you double-click your registered files. You need some way to find out if there is another existing process running already and then communicate with that existing process, if there is one.

Fortunately, there is a class in the .NET Framework that already does all of the hard work for you:

Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase

See this blog for a complete example: http://windowsclient.net/blogs/suryahg/archive/2008/08/20/use-of-microsoft-visualbasic-applicationservices-part-2.aspx

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Harvey Kwok
  • 11,713
  • 6
  • 37
  • 59
  • I had already planned to check if an instance was running by checking the process name and if so I wouldn't have launched a new instance of the program, but that's probably a bad idea. Anyway, thanks for the link. It solved my problem :) – Iceyoshi Dec 23 '10 at 12:22
1

The technique in this question might help:

C# : how to - single instance application that accepts new parameters?

Community
  • 1
  • 1
Meligy
  • 35,654
  • 11
  • 85
  • 109
  • Thanks for the link, that along with the link posted above helped me solve my problem. Now the application is a single instance one which can load multiple documents all in the same instance ;) – Iceyoshi Dec 23 '10 at 12:22