c# – Graphics CopyFromScreen方法如何复制到位图中?

c# – Graphics CopyFromScreen方法如何复制到位图中?,第1张

概述private void startBot_Click(object sender, EventArgs e){ Bitmap bmpScreenshot = Screenshot(); this.BackgroundImage = bmpScreenshot;}private Bitmap Screenshot(){ // This is wh
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,Screen.PrimaryScreen.Bounds.Size);    // Return the screenshot    return bmpScreenshot;}

我最近一直在使用C#,我只是按照一些教程,我只是不明白我是如何擦除图形g它不会把图像作为背景,但代码从来没有分配变量之间的任何关系,除了Graphics g = Graphics.FromImage(bmpScreenshot),然后g给出一些参数,但是然后我们返回bmpScreenshot,这没有任何意义,我希望g被返回?

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

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

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

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

using (var g = Graphics.FromImage(bmpScreenshot)) {      g.copyFromScreen(0,Screen.PrimaryScreen.Bounds.Size);      return bmpScreenshot;  }
总结

以上是内存溢出为你收集整理的c# – Graphics CopyFromScreen方法如何复制到位图中?全部内容,希望文章能够帮你解决c# – Graphics CopyFromScreen方法如何复制到位图中?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1219287.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存