c#winforms:获取必须在控件后面的屏幕截图

时间:2009-09-01 13:35:18

标签: winforms user-interface image controls bitmap

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

H-E-L-P !!!

2 个答案:

答案 0 :(得分:1)

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

  • 将按钮置于不可见
  • 捕获当前屏幕
  • 捕获裁剪到按钮
  • 的clientRectangle的裁剪屏幕
  • 重新设定按钮。

    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();
            }
        }
    }
    

答案 1 :(得分:0)

这很容易做到。窗体上的每个控件都有一个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),其中包含该控件下方的背景图像部分。

抱歉,我不能在代码中更具体 - 我在公共终端。但是intellisense信息会告诉你需要传递什么来绘制DrawImage方法。