【问题标题】:How could I make the bitmap image by using fromHdc method?如何使用 fromHdc 方法制作位图图像?
【发布时间】:2012-10-31 05:25:37
【问题描述】:

我想通过如下代码获取DesktopWindow句柄的方式来获取特定区域。

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

    [DllImport("user32.dll")]
    static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags);

    [DllImport("user32.dll")]
    static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

    public void ScreenShot()
    {
        try
        {
            IntPtr hwnd = GetDesktopWindow();
            IntPtr hdc = GetDCEx(hwnd, IntPtr.Zero, 1027);

            Point temp = new Point(40, 40);
            Graphics g = Graphics.FromHdc(hdc);
            Bitmap bitmap = new Bitmap(mPanel.Width, mPanel.Height, g);

            g.CopyFromScreen(PointToScreen(temp) , PointToScreen(PictureBox.Location) ,  PictureBox.Size);

}

这段代码确实有效,但我想得到一个复制的图像,它是从 CopyFromScreen 的过程中制作的。我曾尝试使用 Graphics.FromImage(bitmap) 之类的代码,但是我无法获得我想要的图像......我的意思是,复制了 Image。 当我使用来自 Hdc 的 Graphics 对象时,我找不到获取位图图像的方法。 我必须使用DC....有什么合适的方法吗??

【问题讨论】:

    标签: c# image graphics bitmap gdi


    【解决方案1】:

    您在这里走错路了,您不需要获取桌面句柄,CopyFromScreen 会将现在屏幕上的任何内容复制到目标图形,因此您需要从图像创建图形对象。 以下代码创建了屏幕左上角的 500x500 图像。

    public static void ScreenShot()
    {
        var destBitmap = new Bitmap(500, 500);
        using (var destGraph = Graphics.FromImage(destBitmap))
        {
            destGraph.CopyFromScreen(new Point(), new Point(), destBitmap.Size);
        }
        destBitmap.Save(@"c:\bla.png");
    }
    

    如果你真的有 HDC,你需要使用 gdi32 中的 BitBlt:

    [DllImport("gdi32.dll")]
    public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
    

    【讨论】:

    • 感谢您的回答,虽然有点晚了(因为我很懒...)我的问题已经完全解决了。
    • 我的回答有帮助还是您以其他方式解决了它? (如果有,请关闭问题)
    猜你喜欢
    • 2015-04-13
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多