如何在c#中捕获具有正常宽高比的屏幕图片

时间:2012-02-23 16:56:04

标签: c# screen-capture

我有宽屏显示器,当我通过c#中的win API捕获屏幕图片时,捕获的图片会很宽。但我想采用正常宽高比1:1的图片。 我不想先拍照,然后调整尺寸,因为图像上的项目会格格不入。

我怎么能这样做?这有可能吗?

我正在使用此代码:

    public static Bitmap GetDesktopImage()
    {
        //In size variable we shall keep the size of the screen.

        SIZE size;


        IntPtr  hDC = PlatformInvokeUSER32.GetDC(PlatformInvokeUSER32.GetDesktopWindow()); 


        IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC);


        do{
        size.cx = PlatformInvokeUSER32.GetSystemMetrics(PlatformInvokeUSER32.SM_CXSCREEN);

        size.cy = PlatformInvokeUSER32.GetSystemMetrics(PlatformInvokeUSER32.SM_CYSCREEN);



            m_HBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC, size.cx, size.cy);

        } while (m_HBitmap == IntPtr.Zero);
        if (m_HBitmap!=IntPtr.Zero)
        {
            IntPtr hOld = (IntPtr) PlatformInvokeGDI32.SelectObject(hMemDC, m_HBitmap);

            PlatformInvokeGDI32.BitBlt(hMemDC,0, 0,size.cx,size.cy, hDC, 0, 0, PlatformInvokeGDI32.SRCCOPY);
            PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
            PlatformInvokeGDI32.DeleteDC(hMemDC);
            PlatformInvokeUSER32.ReleaseDC(PlatformInvokeUSER32.GetDesktopWindow(), hDC);
            Bitmap res=System.Drawing.Image.FromHbitmap(m_HBitmap);
            PlatformInvokeGDI32.DeleteObject(m_HBitmap);
            return res;

        }

        return null;
    }

2 个答案:

答案 0 :(得分:0)

你需要裁剪部分屏幕。如果没有裁剪,你无法将16:9转换为4:3。

-OR -

将屏幕分辨率更改为4:3分辨率, 拍摄屏幕截图, 改回来。

答案 1 :(得分:0)

在桌面窗口句柄上调用GetWindowRect以获取大小。我认为您使用的GetSystemMetric调用不会考虑菜单栏等。