admin管理员组

文章数量:1558697

截取电脑屏幕全屏:



1.程序集代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

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

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

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

        public static Bitmap GetScreen(string path="")
        {
            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);
            }
            //判断路径是否为空或者非法
            if (path != "")
            {
                Regex regex = new Regex(@"^([a-zA-Z]:\\)?[^\/\:\*\?\""\<\>\|\,]*$");
                Match m = regex.Match(path);
                if (!m.Success)
                {
                    return bmp;
                }
                string pathroot= System.IO.Path.GetDirectoryName(path);
                if (System.IO.Directory.Exists(pathroot))
                    bmp.Save(path);
                else
                {
                    System.IO.Directory.CreateDirectory(pathroot);
                    bmp.Save(path);
                }
            }         
            return bmp;
        }
    }
}

2.UI代码


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace PrintScreen
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }
      


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

         

            pictureBox1.Image = PrintScreen.cdll.GetScreen(this.textBox1.Text);
            if (cbHide.Checked)
            {
                this.Show();
            }
        }
    }
}

资源链接:包含labview的demo链接

本文标签: 全屏自适应电脑屏幕代码方法