如何将参数发送到C#中正在运行的进程?

这个问题在这里已经有了答案:

  • 创建单实例应用程序的正确方法是什么? 35个答案

  • 我使用这个:https://code.msdn.microsoft.com/windowsapps/CSWinFormSingleInstanceApp-d1791628

    它是单一实例,并支持命令行参数。 我的程序是这样开始的:

    [STAThread]
    static void Main(String [] args) {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
    
        Form1 mf = new Form1(); // your form
        SingleInstanceAppStarter.Start(mf, StartNewInstance);
    }
    
    ...
    
    private static void StartNewInstance(object sender, StartupNextInstanceEventArgs e) {
        String cmdArg = e.CommandLine[1]; // yes, 1 to get the first.  not zero.
        ...
    }
    

    你还需要这个:

    class SingleInstanceAppStarter
    {
        static SingleInstanceApp app = null;
    
        public static void Start(Form f, StartupNextInstanceEventHandler handler)
        {
            if (app == null && f != null)
            {
                app = new SingleInstanceApp(f);
            }
            app.StartupNextInstance += handler;
            app.Run(Environment.GetCommandLineArgs());
        }
    }
    

    和这个:

    class SingleInstanceApp : WindowsFormsApplicationBase
    {
        public SingleInstanceApp() { }
    
        public SingleInstanceApp(Form f)
        {
            base.IsSingleInstance = true;
            this.MainForm = f;
        }
    }
    

    请注意,这两个类都使用Microsoft.VisualBasic.ApplicationServices程序集(您必须参考它)。

    链接地址: http://www.djcxy.com/p/51153.html

    上一篇: How to send arguments to a running Process in C#?

    下一篇: Use already running application