简体   繁体   中英

Pass arguments given to an already open instance of the same program in C#

I'm currently learning C#, and I'm trying to make a program that puts an already open instance of it on top, but make it pass the arguments it was given to the open instance before closing.

I understand how to make it close if an instance of it is running already, but is there any way to pass arguments to an already running instance?

The code:

using System;
using System.Windows.Forms;
using System.Web;

namespace fart
{
    public static class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form form = new Form();
            TextBox label = new TextBox();
            label.Location = new System.Drawing.Point(0, 0);
            label.Size = new System.Drawing.Size(500, 50);
            if (args.Length == 0)
            {
                label.Text = "no args";
            } else
            {
                args[0] = args[0].Substring(4);
                if (args[0] == "") {
                    label.Text = "args are empty";
                } else
                {
                    label.Text = HttpUtility.UrlDecode(args[0]);
                }
            }
            form.Controls.Add(label);
            Application.Run(form);
        }
    }
}

If the program is already running, then the short answer is "no", at least - not as exe arguments; you do have some limited options, however:

  • if your program started it , it can redirect stdin/stdout and use that as a comms channel
  • otherwise, you're in IPC territory, so: sockets, named pipes, or similar as a comms channel (perhaps using gRPC, WCF or similar so you don't have to deal with all the details)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM