同时运行两个 winform 窗口 [英] Run two winform windows simultaneously

查看:125
本文介绍了同时运行两个 winform 窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 enough in how they operate to share the same resources (methods, data models, assemblies, etc) in the project.

两种形式都已完成,但现在我不确定如何运行该程序,以便每个窗口在启动时打开并独立运行.该程序在部署时将永远在线".

Both forms are complete, but now I'm not sure how to run the program so that each window opens on launch and runs independently. The program will be "always-on" when deployed.

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

This might seem a little basic, but most of my development experience has been web applications. Threading/etc is still a little foreign to me. I've researched but most of the answers I've found relate to user interaction and sequential use cases -- this will just be one system continuously running two distinct processes, which will need to interact with the world independently.

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

Potential solutions I've found might involve multi-threading, or maybe some kind of MDI, or a few folks have suggested the DockPanelSuite (although being in a super-corporate environment, downloading third party files is easier said than done).

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());
    }
}

推荐答案

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

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()));

这篇关于同时运行两个 winform 窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆