C# 截取电脑屏幕

用C#实现一个简单的电脑截屏功能;

aef96b182e444bb1801169810d4a244d.png

实现功能:

    • 截取当前屏幕并显示到页面

开发环境:

开发工具:Visual Studio 2013

.NET Framework版本:4.5

实现代码:

#region 使用WinApi获取正确的分辨率
[DllImport("User32.dll", EntryPoint = "GetDC")]
private extern static IntPtr GetDC(IntPtr hWnd);


[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);


const int DESKTOPVERTRES = 117;
const int DESKTOPHORZRES = 118;
#endregion


private void btnCap_Click(object sender, EventArgs e)
{
    if (cbHide.Checked)
    {
        this.Hide();
        //从显示到隐藏需要有个反应时间
        Thread.Sleep(200);
    }


    //获取屏幕大小的几种方式,具体效果可自行测试
    // Screen.PrimaryScreen.Bounds
    // SystemInformation.PrimaryMonitorMaximizedWindowSize
    // SystemInformation.PrimaryMonitorSize
    // SystemInformation.WorkingArea
    // SystemInformation.VirtualScreen


    //此处不使用以上方式,因为在DPI有调整的情况下,获取到的分辨率有问题
    IntPtr hdc = GetDC(IntPtr.Zero);
    int w = GetDeviceCaps(hdc, DESKTOPHORZRES);
    int h = GetDeviceCaps(hdc, DESKTOPVERTRES);


    Bitmap bmp = new Bitmap(w,h, PixelFormat.Format32bppRgb);


    using (Graphics g = Graphics.FromImage(bmp))
    {
        //绘制屏幕
        g.CopyFromScreen(0, 0, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
    }


    pictureBox1.Image = bmp;
    if (cbHide.Checked)
    {
        this.Show();
    }
}

实现效果:

7a7fbde06aa7b5ae08dfa704480040f2.gif

实现代码比较简单,主要是用到了CopyFromScreen这个方法来实现,其中其中要注意的是我们要考虑到正确获取分辨率的问题,此外,也可以根据坐标直接获取窗口的截图。

由简入繁,拿来即用

后续精彩,持续关注

欢迎关注公众号: dotnet编程大全

技术群: 需要进技术群的添加小编微信mm1552923,备注:加群;

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值