Bitmap.Save整个法师是黑色的,而不仅仅是背景

时间:2016-07-25 17:08:57

标签: c# bitmap save

我目前正在使用PrintWindow截取外部应用程序的屏幕截图,我想将其保存到桌面。

这是我的代码:

// Get proc
            Process proc = Process.GetProcessesByName("procName").Single();
            IntPtr hWnd = proc.MainWindowHandle;

            // Restore proc if minimised
            int style = GetWindowLong(hWnd, GWL_STYLE);
            if ((style & WS_MINIMIZE) == WS_MINIMIZE)
                ShowWindow(hWnd, WindowShowStyle.Restore);

            // Get RECT
            RECT rect;
            GetWindowRect(new HandleRef(this, hWnd), out rect);

            // Get screenshot
            int width = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;
            Bitmap bmp = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                IntPtr dc = g.GetHdc();

                if (!PrintWindow(hWnd, dc, 0))
                {
                    int error = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                    return;
                }

                //Thread.Sleep(200);
                bmp.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.jpeg", ImageFormat.Jpeg);
                panel1.BackgroundImage = bmp;
                g.ReleaseHdc(dc);
            }

panel1向我展示了良好的图像,应用程序的实际屏幕截图。当我去我的桌面时,我找到了一个test.jpeg,但它全是黑色的。为什么呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

我已成功将其保存为.jpg,方法是将代码更改为:

// Get screenshot
            int width = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;
            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
                IntPtr dc = g.GetHdc();

                if (!PrintWindow(hWnd, dc, 0))
                {
                    int error = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                    return;
                }

                g.ReleaseHdc(dc);
            }

            // Save the screenshot
            bmp.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.jpg", ImageFormat.Jpeg);
            panel1.BackgroundImage = bmp;