c#如何实现同时启动两个窗体程序?
1、同时启动多个窗口类,首先输入代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
2、然后输入代码
namespace MVCProject
{
/// <summary>
/// 多窗口同时启动类
/// <remarks>继承ApplicationContext的原因是Application.Run(ApplicationContext context);参数的需要</remarks>
/// <remarks>另一个是关闭同时启动的窗口</remarks>
/// </summary>
3、然后输入代码:
class MultiFormApplictionStart : ApplicationContext
{
private void onFormClosed(object sender, EventArgs e)
{
if (Application.OpenForms.Count == 0)
{
ExitThread();
}
}
public MultiFormApplictionStart()
{
/*
*里面添加启动的窗口
*/
var formList = new List<Form>(){
new DJControl(),
new DJView()
};
foreach (var item in formList)
{
item.FormClosed += onFormClosed;
}
foreach (var item in formList)
{
item.Show();
}
}
}
}
4、最后在Program的类中调用这个类即可
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MultiFormApplictionStart());
}
}
5、然后下方就是效果图:
1)新建建一个“Windows 窗体应用程序”项目。项目中带一个窗体Form1
2)再向项目中添加一个窗体Form2
3)在Form1的后台代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//加载并显示Form2
Form2 f2 = new Form2();
f2.Show();
}
}
}
这样,就实现了同时启动两个窗体程序
2)再向项目中添加一个窗体Form2
3)在Form1的后台代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//加载并显示Form2
Form2 f2 = new Form2();
f2.Show();
}
}
}
这样,就实现了同时启动两个窗体程序