c# - CopyFromScreen 返回表单后面的任何图像

标签 c# windows winforms

我这里有一个严重的问题。我正在编写一个工具,用户可以在其中为开关设备设计控制柜。隔间是用面板和图片框绘制的,效果很好,看起来也不错。

现在我想制作一个导出功能,将设计好的隔间导出到 pdf 文件中。

到目前为止一切顺利,该功能有效 - 仅在我的电脑上可用! 我使用 CopyFromScreen 获取显示隔间的面板的屏幕截图,将其保存到文件中并将其放入 pdf 文件中(我还尝试使用 DrawToBitmap 获取面板的图片,但这无法正常工作,因为它正在绘制一些 Pictureboxes over others)。在我的电脑上,它正确地捕获了面板并在 pdf 中显示了正确的图片,但是在其他每台电脑上,它都拍摄了表格背后的图片。这非常令人困惑,因为我不知道为什么它应该这样做以及它为什么在我的系统上工作。到目前为止,我尝试了一些方法来强制窗口在最上面,但没有任何效果,每个人都得到桌面或后面窗口的图片。

代码:

void takeScreenshot()
    {
        this.TopMost = true;
        this.BringToFront();
        this.Focus();
        Application.DoEvents();

        System.Drawing.Rectangle bounds = Mainpanel.Bounds;
        bounds.Width = bounds.Width - 6;
        bounds.Height = bounds.Height - 4;
        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(Mainpanel.PointToScreen(new Point()).X + 3, Mainpanel.PointToScreen(new Point()).Y + 2, 0, 0, bounds.Size);
            }
            bitmap.Save(Application.StartupPath + "\\data\\programdata\\temppic.bmp");
        }
        this.TopMost = false;
    }

我其实挺绝望的,没有导出程序就没用了。

有没有人知道如何解决这个问题?

乔纳森

最佳答案

使用此代码。

void takeScreenshot()
    {
        Application.DoEvents();
        System.Drawing.Rectangle bounds = Mainpanel.Bounds;
        bounds.Width = bounds.Width - 6;
        bounds.Height = bounds.Height - 4;

        using (Bitmap bitmap = new Bitmap(Mainpanel.Width, Mainpanel.Height))
        {
            Mainpanel.DrawToBitmap(bitmap, new Rectangle(3, 2, bounds.Width, bounds.Height));
            bitmap.Save(Application.StartupPath + "\\data\\programdata\\temppic.bmp");
        }
    }

关于c# - CopyFromScreen 返回表单后面的任何图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18609464/

相关文章:

c# - 如何将默认 Web API 2 更改为 JSON 格式化程序?

c - 无法在 Windows 8 上使用 MinGW 执行 execl()

c# - 修复 Windows 窗体中的拆分容器控件

c# - 向 Windows 窗体消息循环发送或发布消息

C# 类对象覆盖

c# - 如何将字符串的值设置为空

c# - 将颜色动态绑定(bind)到 Xamarin Shape

C# 将字符串转换为 ASCII 字节

python - 是否可以直接在ODBC连接字符串中指定驱动程序dll?

linux - 在 bash 脚本中获取文件夹路径以在 Windows 上工作