运行多个Windows窗体应用程序实例

时间:2013-08-09 12:08:09

标签: c# .net winforms multiple-instances

我决定创建一个聊天应用程序,我需要单个表单运行2次(即)我需要在运行它时查看同一个表单作为两个不同的实例...是否有可能实现它。 / p>

注意:我不需要在任何事件中完成它。每当我运行程序时,必须运行2个实例。

2 个答案:

答案 0 :(得分:4)

两种解决方案:

  • 只需构建可执行文件并根据需要运行尽可能多的实例。
  • 使用更复杂的解决方案,使用Application.Run Method (ApplicationContext)。请参阅下面的简化MSDN示例。

    class MyApplicationContext : ApplicationContext
    {
        private int formCount;
        private Form1 form1;
        private Form1 form2;
    
        private MyApplicationContext()
        {
            formCount = 0;
    
            // Create both application forms and handle the Closed event 
            // to know when both forms are closed.
            form1 = new Form1();
            form1.Closed += new EventHandler(OnFormClosed);
            formCount++;
    
            form2 = new Form1();
            form2.Closed += new EventHandler(OnFormClosed);
            formCount++;
    
            // Show both forms.
            form1.Show();
            form2.Show();
        }
    
        private void OnFormClosed(object sender, EventArgs e)
        {
            // When a form is closed, decrement the count of open forms. 
    
            // When the count gets to 0, exit the app by calling 
            // ExitThread().
            formCount--;
            if (formCount == 0)
                ExitThread();
        }
    
        [STAThread]
        static void Main(string[] args)
        {
    
            // Create the MyApplicationContext, that derives from ApplicationContext, 
            // that manages when the application should exit.
    
            MyApplicationContext context = new MyApplicationContext();
    
            // Run the application with the specific context. It will exit when 
            // all forms are closed.
            Application.Run(context);
        }
    }
    

答案 1 :(得分:1)

是的,您可以轻松创建同一表单的多个实例。例如:

new ChatWindowForm.Show();

另请参阅Control.Show()方法文档。