I'm creating app which has to open files from Explorator. Of course I can do it using args but Explorator opens new app for every file. I'd like to for example send args to existing app - don't open new.
Explorer always opens up a new instance of your application. What you need to do is control whether there's any other open instance, and if it is, pass the command line to it and close your new instance.
There are some classes that may help you in the .NET framework, the easiest way is adding a reference to Microsoft.VisualBasic
(should be in the GAC... and disregard the name, it works for C# too), then you can derive from WindowsFormsApplicationBase
, which does all the boilerplate code for you.
Something like:
public class SingleAppInstance : WindowsFormsApplicationBase
{
public SingleAppInstance()
{
this.IsSingleInstance = true;
this.StartupNextInstance += StartupNextInstance;
}
void StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
{
// here's the code that will be executed when an instance
// is opened.
// the command line arguments will be in e.CommandLine
}
protected override void OnCreateMainForm()
{
// This will be your main form: i.e, the one that is in
// Application.Run() in your original Program.cs
this.MainForm = new Form1();
}
}
Then in your Program.cs
, instead of using Application.Run
, at startup, we do:
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
var singleApp = new SingleAppInstance();
singleApp.Run(args);
}