c# - 运行 Windows 窗体应用程序的多个实例

标签 c# .net winforms multiple-instances

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

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

最佳答案

两种解决方案:

  • 只需构建您的可执行文件并根据需要运行尽可能多的实例。
  • 使用更复杂的解决方案,利用 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);
        }
    }
    

关于c# - 运行 Windows 窗体应用程序的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146291/

相关文章:

c# - 不确定我是否在 tftp 应用程序中正确使用 "using"c#

c# - 用 C# 编写插件或插件框架

c# - 为什么第二个 for 循环总是比第一个循环执行得更快?

winforms - 如何右对齐菜单中的快捷键?

c# - 是否可以从动态数据表构建对象?

c# - C# 和 VB.Net 中同一程序的溢出行为差异

c# - 根据其他列表的结果计算的 TimeSpan 列表

.net - 签署开源项目的二进制文件

c# - Monitor.Wait 和 "exitContext"参数

c# - 具有语法高亮显示的文本框/富文本框? [C#]