C#实现程序一次打开两个窗口,两个窗口分别放置在两个屏幕
这是本人在编程中碰到的一个问题,寻找了其他案例,都只是同时打开两窗口,但不能实现在拥有两块显示屏时候,分别将两个不同的窗口显示在两个单独的屏幕。
源代码https://download.****.net/download/qq_42237381/10728021
实现的方法是添加一个类,这个类中的代码功能是使两个窗口同时运行
定义一个集合,将Form1和Form2放入集合,foreach遍历集合便可以实现同时打开两窗口功能,
var formlist = new List<Form>() { new Form1(), new Form2() };
foreach (var item in formlist)
{
item.Show();
}
Screen函数是关于当前显示屏幕的集合,这样将窗口启动的起始位置设置为某块屏幕就能实现功能
Screen[] sc = Screen.AllScreens;
设定窗口起始位置StartPosition属性由窗口的位置location属性决定,使用下面的语句就可以
f2.StartPosition = FormStartPosition.Manual;
然后在将窗口的位置属性location设置到屏幕2上
f2.Location = new Point(sc[1].Bounds.Left, sc[1].Bounds.Top);
这样就可以实现需求了
具体操作如下
- 首先新建项目,窗口程序
此时已经有一个窗口Form1,这时在解决方案管理器窗口右键项目名称添加一个窗口类Form2
再和上面操作一样添加一个类class1.cs
类里面写运行两窗口的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace TwoWinform
{
class class1 : ApplicationContext
{
private void onFormClose(object sendr, EventArgs e)
{
if (Application.OpenForms.Count == 0)
{
ExitThread();
}
}
public class1()
{
Screen[] sc = Screen.AllScreens;
////窗口2显示在屏幕2
Form2 f2 = new Form2();
f2.StartPosition = FormStartPosition.Manual;
f2.Location = new Point(sc[1].Bounds.Left, sc[1].Bounds.Top);
var formlist = new List<Form>() { new Form1(), f2 };
foreach (var item in formlist)
{
item.Show();
}
}
}
}
再修改程序启动类program使运行class1.cs即可
using Microsoft.VisualBasic;
namespace AntiUAV
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new class1()) ;//运行双窗口类
}
}
}
此案例可以应用到很多地方,比如超市收款机上两屏幕,解决一个对客户,一个对收款员两个显示不同情况下的需求。
此案例可以扩展到多个屏幕,不管多少屏幕都能实现。