1、引入非托管dll

将user32.dll拷贝到指定目录,注意只有托管dll才可引用,而user32.dll为非托管dll,需采取
DllImportAttribute 类,示例代码如下:
using System;
using System.Runtime.InteropServices;
class Example
{
   #region Win32 API
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        static extern IntPtr GetDC(IntPtr ptr);
        [DllImport("User32.dll")]
        private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
        #endregion
}
2、获取桌面大小
public static Size DESKTOP
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                Size size = new Size();
                size.Height = GetDeviceCaps(hdc, 117);
                size.Width = GetDeviceCaps(hdc, 118);
                ReleaseDC(IntPtr.Zero, hdc);
                return size;
            }
        }
3、抓取屏幕图像
private Bitmap GetScreenImage()
        {
            Rectangle viewRect = Screen.PrimaryScreen.Bounds;
            Size phisicalRect = DESKTOP;
            Bitmap srcBmp = new Bitmap(phisicalRect.Width, phisicalRect.Height);
            Graphics gp = Graphics.FromImage(srcBmp);
            gp.CopyFromScreen(0, 0, 0, 0, phisicalRect);
            if (viewRect.Size != phisicalRect)
            {
                Bitmap viewBmp = new Bitmap(viewRect.Width, viewRect.Height);
                Graphics gp1 = Graphics.FromImage(viewBmp);
                gp1.DrawImage(srcBmp, new Rectangle(0, 0, viewRect.Width, viewRect.Height), 0, 0, phisicalRect.Width, phisicalRect.Height, GraphicsUnit.Pixel);
                return viewBmp as Bitmap;
            }
            else
            {
                return srcBmp;
            }
        }
4、保存图片文件
        private void button_start_click(object sender, EventArgs e)
        {
            Bitmap bitmap = GetScreenImage();
            bitmap.Save(@"C:\Users\huguofeng\source\repos\demo\test\screen.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
        }
5、检查文件

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐