C#& Screen 类&(&多&屏&幕&开&发)

2021-05-29 06:00

阅读:515

Screen 类

下面的代码示例演示如何使用 Screen 类的各种方法和属性。 该示例调用 AllScreens 属性来检索连接到系统的所有屏幕的数组。 对于每个返回的 Screen,该示例将设备名称、边界、类型、工作区和主屏幕添加到 ListBox。

技术图片
 1 private void button1_Click(object sender, System.EventArgs e)
 2   {
 3       int index;
 4       int upperBound; 
 5   
 6       // Gets an array of all the screens connected to the system.
 7   
 8   
 9       Screen [] screens = Screen.AllScreens;
10       upperBound = screens.GetUpperBound(0);
11   
12       for(index = 0; index 13       {
14   
15           // For each screen, add the screen properties to a list box.
16   
17   
18           listBox1.Items.Add("Device Name: " + screens[index].DeviceName);
19           listBox1.Items.Add("Bounds: " + screens[index].Bounds.ToString());
20           listBox1.Items.Add("Type: " + screens[index].GetType().ToString());
21           listBox1.Items.Add("Working Area: " + screens[index].WorkingArea.ToString());
22           listBox1.Items.Add("Primary Screen: " + screens[index].Primary.ToString());
23   
24       }
25   
26   }
技术图片

所谓的分屏或多屏软件,就是把软件中的多个窗体,在主屏幕运行,但是把各个窗体(坐标)移动到各个扩展屏幕位置上如下图所示:

?

主屏幕
(MainForm)
index=0
扩展屏幕1
(Form1)
index=1
扩展屏幕2
(Form2)
index=...
扩展屏幕3
(Form3)
index=...

?

?

以下介绍最常用的双屏幕显示,也就是左右模式的屏幕显示的方法。

WinForm 的实现办法:

利用WinForm中的Screen类,即可比较方便地实现多窗体分别在多个屏幕上显示。

?

  • 获取当前系统连接的屏幕数量:?Screen.AllScreens.Count();
  • 获取当前屏幕的名称:string CurrentScreenName = Screen.FromControl(this).DeviceName;
  • 获取当前屏幕对象:Screen CurrentScreen = Screen.FromControl(this);
  • 获取当前鼠标所在的屏幕:Screen CurrentScreen = Screen.FromPoint(new Point(Cursor.Position.X, Cursor.Position.Y));
  • 让窗体在第2个屏幕上显示:
? ? ?this.Left = ((Screen.AllScreens[1].Bounds.Width - this.Width) / 2);
? ? ?this.Top = ((Screen.AllScreens[1].Bounds.Height - this.Height) / 2);
把任何窗体显示在任何屏幕的方法:
Winform:
技术图片
1 Screen[] sc;
2             sc = Screen.AllScreens;
3             this.StartPosition = FormStartPosition.Manual;
4             this.Location = new Point(sc[1].Bounds.Left, sc[1].Bounds.Top);
5             // If you intend the form to be maximized, change it to normal then maximized.
6             this.WindowState = FormWindowState.Normal;
7             this.WindowState = FormWindowState.Maximized;
8             MessageBox.Show(this.Handle.ToString());
技术图片

WPF:

技术图片
 1 protected override void OnStartup(StartupEventArgs e)
 2         {
 3             base.OnStartup(e);
 4 
 5             Window1 w1 = new Window1();
 6             Window2 w2 = new Window2();
 7 
 8 
 9             Screen s1 = Screen.AllScreens[0];
10             Screen s2 = Screen.AllScreens[1];
11 
12             Rectangle r1 = s1.WorkingArea;
13             Rectangle r2 = s2.WorkingArea;
14 
15             w1.Top = r1.Top;
16             w1.Left = r1.Left;
17 
18             w2.Top = r2.Top;
19             w2.Left = r2.Left;
20 
21             w1.Show();
22             w2.Show();
23 
24             w2.Owner = w1;
25 
26 
27         }
技术图片


评论


亲,登录后才可以留言!