如何正确修改“PrimaryScreen”为“AllScreens”?

本文关键字:AllScreens PrimaryScreen 何正确 修改 | 更新日期: 2023-09-27 18:17:08

我有一个叫做Print()的方法,当我调用它时,它会从主屏幕上从一点到另一点的所有像素创建一个位图。

然而,它只在主屏幕上执行(是的,我知道我将其设置为Screen.PrimaryScreen而不是Screen.AllScreens)。

我试过这样做,但是我必须创建一个所有屏幕的数组,这就是我卡住的地方。我该如何实现与这种方法完全相同的东西,但对于多个屏幕?

private void Print()
{
    string path;
    path = "%AppData%''Image.png";
    path = Environment.ExpandEnvironmentVariables(path);
    Bitmap bt;
    Graphics screenShot;
    bt = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    screenShot = Graphics.FromImage(bt);
    screenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
    bt.Save(path);
}

如何正确修改“PrimaryScreen”为“AllScreens”?

您可以使用Rectangle.Union方法和LINQ组合屏幕边界:

var bounds = Screen.AllScreens.Select(s => s.Bounds).Aggregate(Rectangle.Union);

然后在代码中将Screen.PrimaryScreen.Bounds替换为bounds变量

使用Screens.AllScreens()方法返回一个包含所有屏幕的数组,然后循环遍历该数组:

foreach (var screen in Screens.AllScreens())
{
    bt = new Bitmap(screen.Bounds.Width, screen.Bounds.Height, PixelFormat.Format32bppArgb);
    ....
}

这将占用每个屏幕的单独位图图像。如果你想要所有屏幕的单个位图,那么你需要将这些位图缝合在一起,或者使用Ivan的方法来获得所有屏幕的组合边界。

假设您要从一个点移动到另一个点,那么要获取包含该点的屏幕,您可以使用screen。FromPoint方法。

Screen screen = Screen.FromPoint(point);

如果你用Screen.PrimaryScreen,就用screen