Run two winform windows simultaneously

前端 未结 3 1139
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 09:32

I have two C# winform (.NET 4.0) forms that each run separate but similar automated tasks continuously. Separate in that they are distinct processes/workflows, but similar

3条回答
  •  清歌不尽
    2020-11-28 10:17

    You can create a new ApplicationContext to represent multiple forms:

    public class MultiFormContext : ApplicationContext
    {
        private int openForms;
        public MultiFormContext(params Form[] forms)
        {
            openForms = forms.Length;
    
            foreach (var form in forms)
            {
                form.FormClosed += (s, args) =>
                {
                    //When we have closed the last of the "starting" forms, 
                    //end the program.
                    if (Interlocked.Decrement(ref openForms) == 0)
                        ExitThread();
                };
    
                form.Show();
            }
        }
    }
    

    Using that you can now write:

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MultiFormContext(new Form1(), new Form2()));
    

提交回复
热议问题