C# 捕捉矩形后面的图像

C# 捕捉矩形后面的图像,c#,winforms,C#,Winforms,我已经写了一个小应用程序,它将在我的工作环境中用于裁剪图像。包含图像的windows窗体(.NET 3.5)有一个透明的矩形,我使用它在图像的某个部分上拖动,然后点击按钮以获取矩形后面的内容 目前我正在使用下面的代码,这给我带来了一些问题,因为它所捕获的区域偏离了很多像素,我认为这与我的CopyFromScreen函数有关 //Pass in a rectangle private void SnapshotImage(Rectangle rect) {

我已经写了一个小应用程序,它将在我的工作环境中用于裁剪图像。包含图像的windows窗体(.NET 3.5)有一个透明的矩形,我使用它在图像的某个部分上拖动,然后点击按钮以获取矩形后面的内容

目前我正在使用下面的代码,这给我带来了一些问题,因为它所捕获的区域偏离了很多像素,我认为这与我的CopyFromScreen函数有关

    //Pass in a rectangle
    private void SnapshotImage(Rectangle rect)
    {
        Point ptPosition = new Point(rect.X, rect.Y);
        Point ptRelativePosition;

        //Get me the screen coordinates, so that I get the correct area
        ptRelativePosition = PointToScreen(ptPosition);

        //Create a new bitmap
        Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);

        //Sort out getting the image
        Graphics g = Graphics.FromImage(bmp);

        //Copy the image from screen
        g.CopyFromScreen(this.Location.X + ptPosition.X, this.Location.Y + ptPosition.Y,   0,  0, bmp.Size, CopyPixelOperation.SourceCopy);
        //Change the image to be the selected image area
        imageControl1.Image.ChangeImage(bmp);  
    }

如果有人能发现为什么当图像被重画时,它有点不对劲,我将永远感激这一点。另外,
ChangeImage
函数也很好-如果我使用表单作为选择区域,它会起作用,但使用矩形会使事情变得更复杂。

您已将屏幕的相对位置检索为
ptRelativePosition
,但您从未实际使用过它-您将矩形的位置添加到表单的位置,这不代表窗体的边框

这是固定的,有一些优化:

// Pass in a rectangle
private void SnapshotImage(Rectangle rect)
{
    // Get me the screen coordinates, so that I get the correct area
    Point relativePosition = this.PointToScreen(rect.Location);

    // Create a new bitmap
    Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);

    // Copy the image from screen
    using(Graphics g = Graphics.FromImage(bmp)) {
        g.CopyFromScreen(relativePosition, Point.Empty, bmp.Size);
    }

    // Change the image to be the selected image area
    imageControl1.Image.ChangeImage(bmp);  
}

有趣的是,这是因为主窗体和图像所在控件之间的空间,以及窗体顶部的工具栏将控件和主窗体顶部分开。为了解决这个问题,我简单地修改了捕获屏幕中的一行来说明这些像素,如下所示:

g.CopyFromScreen(relativePosition.X + 2, relativePosition.Y+48,  Point.Empty.X, Point.Empty.Y, bmp.Size);

干杯

Hm,由于某种原因,它仍然抓取了错误的区域,Y坐标+50。哦,代码中的点名为“relativePosition”,但您将其引用为ptRelativePosition-正如您所知。@AdLib:您可以上传项目或其他内容吗?(很抱歉回复太晚,由于某些原因,我没有收到评论通知。)