开发者

Singleton of a Winform Application but provide parameters?

开发者 https://www.devze.com 2023-04-06 07:49 出处:网络
I have a webform(c#) application that should only be able to run in a single instance. Its also important that if the applcation is started again(click on app icon) then the new parameters should be f

I have a webform(c#) application that should only be able to run in a single instance. Its also important that if the applcation is started again(click on app icon) then the new parameters should be forwarded to the current instance but now application are to be started.

I have ofcouse google the problem and found this : http://www.sanity-free.com/143/csharp_dotnet_single_instance_application.html

This is how I have set it up so far :

public class MyApp : ApplicationContext
{
        private static MyApp _instance;
        private static Mutex 开发者_StackOverflow中文版_mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");

        [STAThread]
        public static void Main(string[] args)
        {
             MyParams params;

             params = ExtractParams(args);

             if (_mutex.WaitOne(TimeSpan.Zero, true))
             {
                  _instance = new MyAppp(params);
                  Application.Run(_instance);
             }
             else
             {
                  _instance.SetParameters(params);
             }
        }
}

The problem with this is that the second time I try to start the program I will get an exception in the else that _instance is null?

What am I doing wrong here?


The .NET assembly Microsoft.VisualBasic.dll contains a class called WindowsFormsApplicationBase. This one can also be used by C# applications and has a property called IsSingleInstance, which can be set to achieve the required behaviour.

At first application start you can register an event handler for further application starts. From the event args you can extract command line parameters of every additional start.

See an example here.


In this case, it's a Inter-process communication (IPC) so _instance doesn't sense. If you want to have IPC, there're some ways to do: socket, namepiped, messaging ...

I think 2 methods are suited:

  1. Get the previous process by the process name -> call P/Invoke EnumWindows method to get the main window handle. Send a message with ID has been registered with RegisterWindowMessage before, to pass parameters.
  2. Create a namedpipe server to listen for the parameters of the new process.
0

精彩评论

暂无评论...
验证码 换一张
取 消