【问题标题】:c# winforms: Getting the screenshot image that has to be behind a controlc# winforms:获取必须在控件后面的屏幕截图图像
【发布时间】:2024-05-14 21:10:03
【问题描述】:

我有 c# windows 窗体,上面有几个控件,部分控件一个接一个。我想要一个函数,它将从表单中输入一个控件,并返回必须在控件后面的图像。例如:如果表单有 backgroundimage 并在其上包含一个按钮 - 如果我将运行此函数,我将获得位于按钮后面的 backgroundimage 部分。任何想法 - 和代码?

H-E-L-P!!!

【问题讨论】:

  • 你能发布一些关于你想要做什么的信息吗?

标签: winforms user-interface image controls bitmap


【解决方案1】:

这是我最初的猜测,但必须进行测试。

  • 使按钮不可见
  • 捕获当前屏幕
  • 裁剪屏幕捕获到按钮的客户端矩形
  • 重新建立按钮。

    public static Image GetBackImage(Control c) {   
        c.Visible = false;
        var bmp = GetScreen();
        var img = CropImage(bmp, c.ClientRectangle);
        c.Visible = true;
    }
    
    public static Bitmap GetScreen() {
        int width = SystemInformation.PrimaryMonitorSize.Width;
        int height = SystemInformation.PrimaryMonitorSize.Height;
    
        Rectangle screenRegion = Screen.AllScreens[0].Bounds;
        var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
        Graphics graphics = Graphics.FromImage(bitmap);
        graphics.CopyFromScreen(screenRegion.Left, screenRegion.Top, 0, 0, screenRegion.Size);
        return bitmap;
    }
    public static void CropImage(Image imagenOriginal, Rectangle areaCortar) {
        Graphics g = null;
        try {
            //create the destination (cropped) bitmap
            var bmpCropped = new Bitmap(areaCortar.Width, areaCortar.Height);
            //create the graphics object to draw with
            g = Graphics.FromImage(bmpCropped);
    
            var rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
    
            //draw the areaCortar of the original image to the rectDestination of bmpCropped
            g.DrawImage(imagenOriginal, rectDestination, areaCortar, GraphicsUnit.Pixel);
            //release system resources
        } finally {
            if (g != null) {
                g.Dispose();
            }
        }
    }
    

【讨论】:

  • 我不认为他想要控件下方和表单背后的图像 - 他只想要控件下方表单上的内容。
  • 我只是让按钮可见,所以效果会得到它后面的图像
【解决方案2】:

这很容易做到。表单上的每个控件都有一个 Size 和一个 Location 属性,您可以使用它们来实例化一个新的 Rectangle,如下所示:

Rectangle rect = new Rectangle(button1.Location, button1.Size);

要获得包含位于控件后面的背景图像部分的位图,首先要创建一个适当尺寸的位图:

Bitmap bmp = new Bitmap(rect.Width, rect.Height);

然后为新的 Bitmap 创建一个 Graphics 对象,并使用该对象的 DrawImage 方法复制背景图像的一部分:

using (Graphics g = Graphics.FromImage(bmp))
{
    g.DrawImage(...); // sorry, I don't recall which of the 30 overloads
        // you need here, but it will be one that uses form1.Image as
        // the source, and rect for the coordinates of the source
}

这将为您留下包含该控件下方背景图像部分的新位图 (bmp)。

抱歉,我无法在代码中更具体 - 我在公共终端。但是智能感知信息会告诉您需要为 DrawImage 方法传递什么。

【讨论】:

    最近更新 更多