C# 截屏

使用 Graphics.CopyFromScreen api实现截屏

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public  class jiePing
{

    [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;

    /// <summary>
    /// 截屏为Bitmap
    /// </summary>
    /// <returns></returns>
    public static Bitmap GetScreenCapture()
    {
        //获取屏幕大小的几种方式,具体效果可自行测试 // 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;
        // image.Source = jiePing.BitmapToBitmapImage(bmp);
        return bmp;
    }

    /// <summary>
    /// 格式转换 bitmap->BitmapImage
    /// </summary>
    /// <param name="bitmap"></param>
    /// <returns></returns>
    public static System.Windows.Media.Imaging.BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
    {
        Bitmap b = new Bitmap(bitmap);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以
        ms.Close();
        //Convert it to BitmapImage
        System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
        image.BeginInit();
        image.StreamSource = new System.IO.MemoryStream(bytes);
        image.EndInit();
        return image;
    }




}

调用

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            image.Source = jiePing.BitmapToBitmapImage( jiePing.GetScreenCapture());
            jiePing.GetScreenCapture().Save("D:/65.png", System.Drawing.Imaging.ImageFormat.Png);
        }

    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值