Graphics CopyFromScreen方法如何复制到位图?

Dat*_*sik 3 c#

private void startBot_Click(object sender, EventArgs e)
{
        Bitmap bmpScreenshot = Screenshot();
        this.BackgroundImage = bmpScreenshot;
}

private Bitmap Screenshot()
{

    // This is where we will store a snapshot of the screen
    Bitmap bmpScreenshot = 
        new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height);

    // Creates a graphic object so we can draw the screen in the bitmap (bmpScreenshot);
    Graphics g = Graphics.FromImage(bmpScreenshot);

    // Copy from screen into the bitmap we created
    g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);

    // Return the screenshot
    return bmpScreenshot;
}
Run Code Online (Sandbox Code Playgroud)

我最近一直在玩C#,我只是按照一些教程,我只是不明白如果我要擦除Graphics g它不会把图像作为背景,但代码在任何时候都没有指定任何变量之间的关系,除了Graphics g = Graphics.FromImage(bmpScreenshot),然后g给出一些参数,但那么我们return bmpScreenshot哪个没有任何意义,我会期望g被返回?

Han*_*ant 7

可以显示图形的设备在Windows中进行虚拟化.该概念在winapi中称为"设备上下文",底层表示是"句柄".Graphics类包装了句柄,它本身不存储像素.注意Graphics.GetHdc()方法,一种获取该句柄的方法.

否则该类只包含在该句柄所代表的设备上产生图形输出的绘图方法.实际设备可以是屏幕,打印机,图元文件,位图.凭借您自己的代码中的巨大优势,它可以用于生成您想要的输出.因此,打印就像将其绘制到屏幕或绘制到存储到文件的位图一样简单.

因此,通过调用Graphics.FromImage(),可以将Graphics对象与位图相关联.它的所有绘制方法实际上都是在位图中设置像素.与CopyFromScreen()一样,它只是将像素从视频适配器的帧缓冲区复制到设备上下文,实际上设置了位图中的像素.因此,此代码的预期返回值是实际位图.应该在发生之前处理Graphics对象,因为它不再有用.或者换句话说,需要释放底层句柄,以便操作系统取消分配其自己的资源以表示设备上下文.

这是代码片段中的一个错误.当Windows拒绝创建更多设备上下文时,重复调用此方法很容易导致程序崩溃.并且垃圾收集器不会以足够快的速度赶上.它应该写成:

  using (var g = Graphics.FromImage(bmpScreenshot)) {
      g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
      return bmpScreenshot;
  }
Run Code Online (Sandbox Code Playgroud)