简体   繁体   中英

How can I capture the screen and ignore a specific window in the image

I want to write a program that will magnify the middle of the screen, so I used some methods from user32.dll. I managed to make my program capture the screen and refresh the image on the picturebox with 60FPS rate, but when I want to display in real time the bigger image, the program also captures my forms which displays the bigger image, thus leading to an infinite image inside an image loop. I want to capture the screen and ignore my form which displays the bigger image.

I thought about something like I pass it the handle of the window I want to ignore and it will capture anything but the window i specified. This is my code for now:

Bitmap CaptureWindow(IntPtr handle)
{
    IntPtr hdcSrc = User32.GetWindowDC(handle);
    User32.RECT windowRect = new User32.RECT();
    User32.GetWindowRect(handle, ref windowRect);
    int width = windowRect.right - windowRect.left;
    int height = windowRect.bottom - windowRect.top;
    IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
    IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
    IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);

    GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
    GDI32.SelectObject(hdcDest, hOld);
    GDI32.DeleteDC(hdcDest);
    User32.ReleaseDC(handle, hdcSrc);

    Bitmap img = null;
    try
    {
        img = new Bitmap(Image.FromHbitmap(hBitmap), 1920 * 2, 1080 * 2);              
        using (Graphics g = Graphics.FromImage(img))
        {
            g.FillRectangle(Brushes.White, new Rectangle(0, 0, 200, 1080));//img.Width - (img.Height/2), img.Height));
            // g.FillRectangle(Brushes.White, new Rectangle(img.Width - (img.Height / 2) + img.Height, 0, img.Width - img.Height / 2, img.Height));
        }
        GDI32.DeleteObject(hBitmap);            
    }
    catch (Exception e)
    { }
    return img;
}

The handle I pass it is from this method:

[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();

I already tried this solution: How can i capture the screen without the Form? but it didn't work well because the picturebox refreshes at 60Hz rate which causes it to stutter.

To be clear, my idea is to magnify the middle of the screen and then display the magnified image in a square in the middle of the screen (the areas outside the square will be left with their original size).

When you capture the initial image, blank out the area that corresponds to inside your form by drawing a rectangle over the same area. You can get the window position and dimensions via the Form and draw the rectangle over that portion of the captured image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM