Pass arguments to running application

前端 未结 5 1020
猫巷女王i
猫巷女王i 2020-12-01 08:20

I am making an image uploader (upload image to image hosting website) and I\'m having some issues passing an argument (image location to an already running application)

5条回答
  •  天命终不由人
    2020-12-01 09:08

    I added some small additions to the previous solution to reference a setter on the form in order to pass the arguments to it.

    So first of all, create a static reference to the initial instance of the form (MainForm).

    Then, on subsequent sending of arguments, the NewInstanceHandler can use the saved reference to the form to access it's public methods/properties (in my case, a setter called AddItem).

    An easy way to test this out is to add a public property to your form with a setter to change the text property of the form (the title text).

    [STAThread]
        static Form1 MainForm;
    
        static void Main(params string[] Arguments)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm = new Form1();
            SingleInstanceApplication.Run(MainForm, NewInstanceHandler);
        }
    
        public static void NewInstanceHandler(object sender, StartupNextInstanceEventArgs e)
        {
            MainForm.AddItem = e.CommandLine[1];
            e.BringToForeground = false;
        }
    
        public class SingleInstanceApplication : WindowsFormsApplicationBase
        {
            private SingleInstanceApplication()
            {
                base.IsSingleInstance = true;
            }
    
            public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)
            {
                SingleInstanceApplication app = new SingleInstanceApplication();
                app.MainForm = f;
                app.StartupNextInstance += startupHandler;
                app.Run(Environment.GetCommandLineArgs());
            }
        } 
    

提交回复
热议问题