1

我想构建 ac# 应用程序 - 它应该像我在网页中创建链接的方式一样,它应该像 skype 所做的那样,它对传递参数的应用程序执行“调用”操作。我希望该应用程序仅在任务栏中。

所以我第一次启动应用程序,然后下次单击链接时,它将在第一个应用程序上再次执行。

<a href="myapp:12345">Click me</a>

我将设置 Windows 注册表以做出相应的响应,然后它应该使用参数触发应用程序

例如 myapp.exe /12345

我可以使应用程序工作,但每次单击链接时都会获得一个新实例,如何将参数传递给当前正在运行的应用程序?

4

1 回答 1

1

受此启发以防止第二个实例,而这则用于命名管道服务器

static void Main(string[] args)
{

    string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format("Global\\{{{0}}}", appGuid);

    using (var mutex = new Mutex(false, mutexId))
    {

        var hasHandle = false;
        try
        {
            try
            {
                hasHandle = mutex.WaitOne(5000, false);
            }
            catch (AbandonedMutexException)
            {
                hasHandle = true;
            }


            if (hasHandle)
            {
                // main app
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Form1 frm = new Form1();

                HandleArgs(args,frm); // handle first start with args

                Server(appGuid, frm); // handle next clients

                Application.Run(frm);
            }
            else
            {
                //any next client..
                var cli = new NamedPipeClientStream(appGuid);
                // connect to first app
                cli.Connect();
                // serialiaze args and send over
                var bf = new BinaryFormatter();
                bf.Serialize(cli, args);  // the commandline args over the line
                cli.Flush();
                cli.Close();
                // done
            }
        }
        finally
        {
            if (hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

// do usefull stuff with the commandline args
static void HandleArgs(string[] args, Form1 frm)
{
    foreach (var s in args)
    {
        // just append the args to the textbox
        frm.textBox1.Text += s;
        frm.textBox1.Text += Environment.NewLine;
    }
}

// server that runs async
static void Server(string appGuid, Form1 frm)
{
    var srv = new NamedPipeServerStream(appGuid, PipeDirection.InOut, 5, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

    srv.BeginWaitForConnection(state =>
    {
        NamedPipeServerStream nps = (NamedPipeServerStream)state.AsyncState;
        nps.EndWaitForConnection(state);

        var bf = new BinaryFormatter();
        string[] args = (string[])bf.Deserialize(nps);

        // don't forget to call on the UI thread
        frm.Invoke(new MethodInvoker(() => { HandleArgs(args, frm); }));

        nps.Disconnect();

        Server(appGuid, frm); // restart server
    }, srv);
}
于 2013-07-19T19:52:08.120 回答