首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >同时运行两个winform窗口

同时运行两个winform窗口
EN

Stack Overflow用户
提问于 2013-03-09 02:32:38
回答 2查看 37.4K关注 0票数 21

我有两个C# winform (.NET 4.0)表单,每个表单都可以连续运行不同但相似的自动化任务。因为它们是截然不同的流程/工作流,但在操作方式上足够相似,以便在项目中共享相同的资源(方法、数据模型、程序集等)。

这两个表单都已完成,但现在我不确定如何运行该程序,以便每个窗口在启动时打开并独立运行。该程序在部署时将是“始终在线”的。

这可能看起来有点基础,但我的大部分开发经验都是web应用程序。线程/etc对我来说还是有点陌生。我已经研究过了,但我发现的大多数答案都与用户交互和顺序用例有关--这将只是一个系统连续运行两个不同的进程,需要独立地与世界交互。

我发现的潜在解决方案可能涉及多线程,或者可能是某种MDI,或者一些人建议使用DockPanelSuite (尽管在超级企业环境中,下载第三方文件说起来容易做起来难)。

代码语言:javascript
复制
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Rather than specifying frmOne or frmTwo,
        // load both winforms and keep them running.
        Application.Run(new frmOne());
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-09 02:45:31

您可以创建一个新的ApplicationContext来表示多个表单:

代码语言:javascript
复制
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();
        }
    }
}

使用它,你现在可以写:

代码语言:javascript
复制
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MultiFormContext(new Form1(), new Form2()));
票数 42
EN

Stack Overflow用户

发布于 2013-03-09 02:44:38

如果你真的需要两个窗口/窗体在两个单独的UI线程上运行,你可以这样做:

代码语言:javascript
复制
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var thread = new Thread(ThreadStart);
        // allow UI with ApartmentState.STA though [STAThread] above should give that to you
        thread.TrySetApartmentState(ApartmentState.STA); 
        thread.Start(); 

        Application.Run(new frmOne());
    }

    private static void ThreadStart()
    {
        Application.Run(new frmTwo()); // <-- other form started on its own UI thread
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15300887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档