C#winfrom端屏幕截图功能的简单实现(修改了屏幕的缩放比例后,截图功能异常,慎用!!!)

文章目录

  • 1 主要文件
    • 1.1 FrmScreenShot.cs
    • 1.2 FrmScreenShot.Designer.cs
    • 1.1 Utility.cs

在发现有一款播放软件禁止截图功能后,使用了其他的截图工具发现都会被播放软件禁用掉截图功能,想了下试着自己做一个截图工具,也可以方便将截图工具添加在以后的项目中,是制作过程中也考虑到了一台电脑包含多个显示器的情况。

注意:最后发现在修改了屏幕的缩放比例后截图效果异常,由于时间不允许后续有时间再作更新。。

截图效果展示
C#winfrom端屏幕截图功能的简单实现(修改了屏幕的缩放比例后,截图功能异常,慎用!!!)_第1张图片

1 主要文件

屏幕截图中主要文件包含
FrmScreenShot.cs
FrmScreenShot.Designer.cs
Utility.cs

1.1 FrmScreenShot.cs

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace ScreenShot
{
    /// 
    /// 截取到屏幕的图像
    /// 
    public partial class FrmScreenShot : Form
    {

        /// 
        /// 打开截图
        /// 
        public static void OpenShotScreen()
        {
            try
            {
                new FrmScreenShot().Show();
            }
            catch (Exception ex)
            {
                
            }
        }

        private readonly EBoundType[] _AllBoundType =
        {
            EBoundType.Updata_1,
            EBoundType.Updata_2,
            EBoundType.Updata_3,
            EBoundType.Updata_4,
            EBoundType.Updata_5,
            EBoundType.Updata_6,
            EBoundType.Updata_7,
            EBoundType.Updata_8,
            EBoundType.Updata_9,
        };
        private Bitmap _bmp;

        /// 
        /// 鼠标按下、抬起(移动时的位置)
        /// 
        private Point _mouseDownLocation, _mouseUpLocation;

        /// 
        /// 当前选择边角类型
        /// 
        public EBoundType _boundType = EBoundType.Wait;

        /// 
        /// 图像绘制区域
        /// 
        private Rectangle _bitmapDrawRect;

        /// 
        /// 选择的区域(获取到鼠标在屏幕的坐标)
        /// 
        private Rectangle _selectRect, _selectRectLast;

        /// 
        /// 选择区域的边角区域尺寸
        /// 
        private Size _boundAreaWidth = new Size(6, 6);

        public FrmScreenShot()
        {
            InitializeComponent();

            StartPosition = FormStartPosition.WindowsDefaultLocation;

            _bmp = Utility.CopyScreenToImage(out _bitmapDrawRect);
            this.Bounds = _bitmapDrawRect;
            this.DoubleBuffered = true;
        }

        private void FrmScreenBitmap_Load(object sender, EventArgs e)
        {
            this.Location = _bitmapDrawRect.Location;
        }


        [Description("绘图事件")]
        private void FrmScreenBitmap_Paint(object sender, PaintEventArgs e)
        {
            if (_bmp == null) return;

            var font = new Font("微软雅黑", 14F, FontStyle.Regular, GraphicsUnit.Point, 134);

            var g = e.Graphics;
            var bitmapDrawRect = new RectangleF(0, 0, _bitmapDrawRect.Width, _bitmapDrawRect.Height);

            g.Clear(Color.Empty);
            g.SmoothingMode = SmoothingMode.HighQuality; //指定抗锯齿的呈现

            //图像绘制区域
            var drawArea = new RectangleF(0, 0, _bmp.Width, _bmp.Height);
            g.DrawImage(_bmp, bitmapDrawRect, drawArea, GraphicsUnit.Pixel);//绘制图像
            Utility.DrawTransparencyFillRect(g, bitmapDrawRect);

            //绘制未选择区域时最大边框区域
            if (_boundType == EBoundType.Wait)
            {
                var lineWidth = Utility.MPen.Width;
                var rect = new RectangleF
                {
                    X = bitmapDrawRect.X + lineWidth,
                    Y = bitmapDrawRect.Y + lineWidth,
                    Width = bitmapDrawRect.Width - lineWidth * 2,
                    Height = bitmapDrawRect.Height - lineWidth * 2,
                };
                Utility.DrawRect(g, rect);
                g.DrawString($"{bitmapDrawRect.Width} x {bitmapDrawRect.Height}", font, new SolidBrush(Color.White), rect.Location);
            }
            else
            {
                var rect = RectFormat(_selectRect); ;
                var p2 = new PointF(rect.X + rect.Width, rect.Y + rect.Height);
                Utility.DrawRect(g, rect.Location, p2);
                g.DrawImage(_bmp, rect, rect, GraphicsUnit.Pixel); //绘制图像
                foreach (EBoundType type in _AllBoundType)
                {
                    if (type == EBoundType.None || type == EBoundType.Updata_5)
                        continue;
                    Utility.DrawFillRect(g, GetBoundRect(type, rect));
                }

                //绘制当前选区的信息
                string text = $"{rect.Width} x {rect.Height}";
                var textLocation = rect.Location;
                var textHeight = (int)g.MeasureString(text, font).Height;
                textLocation.Y -= textHeight;
                if (textLocation.Y < textHeight)
                {
                    textLocation.Y = rect.Y;
                }
                g.DrawString(text, font, new SolidBrush(Color.White), textLocation);
            }
        }

        [Description("监控所有按键")]
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                Exit();
                return true;
            }
            return false;
        }

        [Description("鼠标按下:选择区域起点")]
        private void Form2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            SetPanControlState(false);

            _mouseDownLocation = e.Location;
            _selectRectLast = _selectRect;

            switch (_boundType)
            {
                case EBoundType.Wait:
                    _boundType = EBoundType.SelectIng;
                    _mouseUpLocation = _mouseDownLocation;
                    break;
                default:
                    _boundType = GetMouseInRectType(_selectRect, e.Location);
                    break;
            }

        }

        [Description("鼠标移动:设置选择区域的尺寸")]
        private void Form2_MouseMove(object sender, MouseEventArgs e)
        {
            _mouseUpLocation = e.Location;
            SetMouseCursor(e.Location);
            switch (_boundType)
            {
                case EBoundType.Updata_1:
                case EBoundType.Updata_2:
                case EBoundType.Updata_3:
                case EBoundType.Updata_4:
                case EBoundType.Updata_6:
                case EBoundType.Updata_7:
                case EBoundType.Updata_8:
                case EBoundType.Updata_9:
                case EBoundType.Updata_5:
                case EBoundType.SelectIng:
                    UpdataSelectRect(_mouseDownLocation, _mouseUpLocation, _boundType);
                    Refresh();
                    break;
            }
        }

        [Description("鼠标抬起:确定选择区域")]
        private void Form2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            _mouseUpLocation = e.Location;
            UpdataSelectRect(_mouseDownLocation, _mouseUpLocation, _boundType);
            _boundType = EBoundType.End;
            _selectRect = RectFormat(_selectRect);
            Refresh();
            SetPanControlState(true);
        }


        [Description("退出截图")]
        private void pic_Exit_Click(object sender, EventArgs e)
        {
            Exit();
        }

        [Description("保存截图")]
        private void pic_Save_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "|*.bmp";
                dialog.FileName = "截图";
                var ret = dialog.ShowDialog() == DialogResult.OK;
                if (ret)
                {
                    Bitmap bmp = Utility.GetImageRect(_bmp, _selectRect);
                    string path = dialog.FileName;
                    _bmp.Save(path, ImageFormat.Bmp);
                    Process.Start(path);
                    Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常");
            }
        }

        /// 
        /// 更新选择区域参数
        /// 
        private void UpdataSelectRect(Point down, Point up, EBoundType boundType)
        {
            switch (boundType)
            {
                case EBoundType.SelectIng:
                    _selectRect.Location = new Point(Math.Min(down.X, up.X), Math.Min(down.Y, up.Y));
                    _selectRect.Size = new Size(Math.Abs(down.X - up.X), Math.Abs(down.Y - up.Y));
                    break;
                case EBoundType.Updata_1:
                    _selectRect.X = _selectRectLast.X + (up.X - down.X);
                    _selectRect.Y = _selectRectLast.Y + (up.Y - down.Y);
                    _selectRect.Width = _selectRectLast.Width + (down.X - up.X);
                    _selectRect.Height = _selectRectLast.Height + (down.Y - up.Y);
                    break;
                case EBoundType.Updata_2:
                    _selectRect.Y = _selectRectLast.Y + (up.Y - down.Y);
                    _selectRect.Height = _selectRectLast.Height + (down.Y - up.Y);
                    break;
                case EBoundType.Updata_3:
                    _selectRect.Y = _selectRectLast.Y + (up.Y - down.Y);
                    _selectRect.Width = _selectRectLast.Width + (up.X - down.X);
                    _selectRect.Height = _selectRectLast.Height + (down.Y - up.Y);
                    break;
                case EBoundType.Updata_4:
                    _selectRect.X = _selectRectLast.X + (up.X - down.X);
                    _selectRect.Width = _selectRectLast.Width + (down.X - up.X);
                    break;
                case EBoundType.Updata_6:
                    _selectRect.Width = _selectRectLast.Width + (up.X - down.X);
                    break;
                case EBoundType.Updata_7:
                    _selectRect.X = _selectRectLast.X + (up.X - down.X);
                    _selectRect.Width = _selectRectLast.Width + (down.X - up.X);
                    _selectRect.Height = _selectRectLast.Height + (up.Y - down.Y);
                    break;
                case EBoundType.Updata_8:
                    _selectRect.Height = _selectRectLast.Height + (up.Y - down.Y);
                    break;
                case EBoundType.Updata_9:
                    _selectRect.Width = _selectRectLast.Width + (up.X - down.X);
                    _selectRect.Height = _selectRectLast.Height + (up.Y - down.Y);
                    break;
                case EBoundType.Updata_5:
                    _selectRect.X = _selectRectLast.X + up.X - down.X;
                    _selectRect.Y = _selectRectLast.Y + up.Y - down.Y;
                    break;
            }

        }

        private Rectangle RectFormat(Rectangle rect)
        {

            if (rect.Width < _bitmapDrawRect.X)
            {
                rect.X += rect.Width;
                rect.Width = Math.Abs(rect.Width);
            }

            if (rect.Height < _bitmapDrawRect.Y)
            {
                rect.Y += rect.Height;
                rect.Height = Math.Abs(rect.Height);
            }

            rect.Location = new Point(Math.Min(Math.Max(0, rect.X), _bitmapDrawRect.Width - rect.Width), Math.Min(Math.Max(0, rect.Y), _bitmapDrawRect.Height - rect.Height));

            return rect;
        }

        /// 
        /// 设置鼠标指针样式
        /// 
        private void SetMouseCursor(Point mouseLotion)
        {
            var cursor = Cursors.Arrow;
            switch (GetMouseInRectType(_selectRect, mouseLotion))
            {
                case EBoundType.Updata_1:
                case EBoundType.Updata_9:
                    cursor = Cursors.SizeNWSE;
                    break;
                case EBoundType.Updata_2:
                case EBoundType.Updata_8:
                    cursor = Cursors.SizeNS;
                    break;
                case EBoundType.Updata_3:
                case EBoundType.Updata_7:
                    cursor = Cursors.SizeNESW;
                    break;
                case EBoundType.Updata_4:
                case EBoundType.Updata_6:
                    cursor = Cursors.SizeWE;
                    break;
                case EBoundType.Updata_5:
                    cursor = Cursors.SizeAll;
                    break;
            }
            this.Cursor = cursor;
        }

        private void Exit() => this.Close();

        /// 
        /// 设置控件位置和装填
        /// 
        private void SetPanControlState(bool mouseUp)
        {
            if (mouseUp)
            {
                var location = _selectRect.Location;
                location.X += _selectRect.Width;
                location.Y += _selectRect.Height + 5;
                location.X -= pan_Control.Width + 5;

                location.X = Math.Max(_selectRect.X, location.X);

                if (location.Y + pan_Control.Height > _bitmapDrawRect.Y + _bitmapDrawRect.Height)
                    location.Y = _selectRect.Y - pan_Control.Height - 5;

                if (location.Y < 0)
                    location.Y = _selectRect.Y + _selectRect.Height - pan_Control.Height - 5;

                pan_Control.Location = location;
            }
            pan_Control.Visible = mouseUp;
        }

        /// 
        /// 获取指定区域当前鼠标所在该区域位置的类型
        /// 
        /// 
        /// 
        private EBoundType GetMouseInRectType(Rectangle rect, Point mouseLotion)
        {
            var location = mouseLotion;
            var areaWidth = 3;

            if (!new Rectangle(rect.X - areaWidth, rect.Y - areaWidth, rect.Width + areaWidth * 2, rect.Height + areaWidth * 2).Contains(location))
                return EBoundType.None;
            foreach (EBoundType type in _AllBoundType)
            {
                var newRect = GetBoundRect(type, rect);
                if (newRect.Contains(location))
                {
                    return type;
                }
            }
            return EBoundType.None;
        }

        /// 
        /// 根据选取类型和指定区域获取选取边界的点的小区域
        /// 
        /// 选取类型
        /// 指定区域
        /// 边界点区域的大小控制
        /// 
        private Rectangle GetBoundRect(EBoundType type, Rectangle rect)
        {
            switch (type)
            {
                case EBoundType.Updata_1:
                case EBoundType.Updata_2:
                case EBoundType.Updata_3:
                case EBoundType.Updata_4:
                case EBoundType.Updata_6:
                case EBoundType.Updata_7:
                case EBoundType.Updata_8:
                case EBoundType.Updata_9:
                    var location = GetBoundPoint(type, rect);
                    var newRect = GetRecttangleByPoint(location);
                    return newRect;
                case EBoundType.Updata_5:
                    return rect;

                default:
                    throw new Exception("空局域");
            }
        }

        /// 
        /// 获取指定区域的指定边角类型对应的点坐标
        /// 
        private Point GetBoundPoint(EBoundType type, Rectangle rect)
        {
            switch (type)
            {
                case EBoundType.Updata_1:
                    return new Point(rect.X, rect.Y);
                case EBoundType.Updata_2:
                    return new Point(rect.X + rect.Width / 2, rect.Y);
                case EBoundType.Updata_3:
                    return new Point(rect.X + rect.Width, rect.Y);
                case EBoundType.Updata_4:
                    return new Point(rect.X, rect.Y + rect.Height / 2);
                case EBoundType.Updata_5:
                    return new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
                case EBoundType.Updata_6:
                    return new Point(rect.X + rect.Width, rect.Y + rect.Height / 2);
                case EBoundType.Updata_7:
                    return new Point(rect.X, rect.Y + rect.Height);
                case EBoundType.Updata_8:
                    return new Point(rect.X + rect.Width / 2, rect.Y + rect.Height);
                case EBoundType.Updata_9:
                    return new Point(rect.X + rect.Width, rect.Y + rect.Height);
                default:
                    throw new Exception("空局域");
            }
        }

        /// 
        /// 获取边角区域的Rectangle
        /// 
        /// 
        /// 
        private Rectangle GetRecttangleByPoint(Point p) => new Rectangle
        {
            X = p.X - _boundAreaWidth.Width / 2,
            Y = p.Y - _boundAreaWidth.Height / 2,
            Size = _boundAreaWidth
        };

    }




    /// 
    /// 鼠标所在区域的类型
    /// 
    public enum EBoundType
    {
        None = 1,
        Updata_1,
        Updata_2,
        Updata_3,
        Updata_4,
        Updata_6,
        Updata_7,
        Updata_8,
        Updata_9,

        /// 
        /// 五号区域标识当前选中区域拖动
        /// 
        Updata_5,

        Wait,
        SelectIng,
        End,
    }

}

1.2 FrmScreenShot.Designer.cs

namespace ScreenShot
{
    partial class FrmScreenShot
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.pic_Save = new System.Windows.Forms.PictureBox();
            this.pic_Exit = new System.Windows.Forms.PictureBox();
            this.pan_Control = new System.Windows.Forms.Panel();
            ((System.ComponentModel.ISupportInitialize)(this.pic_Save)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pic_Exit)).BeginInit();
            this.pan_Control.SuspendLayout();
            this.SuspendLayout();
            // 
            // pic_Save
            // 
            this.pic_Save.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left)));
            this.pic_Save.BackColor = System.Drawing.Color.Transparent;
            this.pic_Save.BackgroundImage = global::截取屏幕.Properties.Resources.对错_对;
            this.pic_Save.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.pic_Save.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.pic_Save.Location = new System.Drawing.Point(44, 0);
            this.pic_Save.Margin = new System.Windows.Forms.Padding(0);
            this.pic_Save.Name = "pic_Save";
            this.pic_Save.Size = new System.Drawing.Size(27, 35);
            this.pic_Save.TabIndex = 3;
            this.pic_Save.TabStop = false;
            this.pic_Save.Click += new System.EventHandler(this.pic_Save_Click);
            // 
            // pic_Exit
            // 
            this.pic_Exit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left)));
            this.pic_Exit.BackColor = System.Drawing.Color.Transparent;
            this.pic_Exit.BackgroundImage = global::截取屏幕.Properties.Resources.对错_错;
            this.pic_Exit.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.pic_Exit.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.pic_Exit.Location = new System.Drawing.Point(9, 0);
            this.pic_Exit.Margin = new System.Windows.Forms.Padding(0);
            this.pic_Exit.Name = "pic_Exit";
            this.pic_Exit.Size = new System.Drawing.Size(27, 35);
            this.pic_Exit.TabIndex = 4;
            this.pic_Exit.TabStop = false;
            this.pic_Exit.Click += new System.EventHandler(this.pic_Exit_Click);
            // 
            // pan_Control
            // 
            this.pan_Control.BackColor = System.Drawing.Color.White;
            this.pan_Control.Controls.Add(this.pic_Exit);
            this.pan_Control.Controls.Add(this.pic_Save);
            this.pan_Control.Location = new System.Drawing.Point(35, 26);
            this.pan_Control.Name = "pan_Control";
            this.pan_Control.Size = new System.Drawing.Size(81, 35);
            this.pan_Control.TabIndex = 5;
            this.pan_Control.Visible = false;
            // 
            // FrmScreenShot
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            this.ClientSize = new System.Drawing.Size(716, 593);
            this.Controls.Add(this.pan_Control);
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Margin = new System.Windows.Forms.Padding(4);
            this.Name = "FrmScreenShot";
            this.ShowInTaskbar = false;
            this.Text = "Form2";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.FrmScreenBitmap_Load);
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.FrmScreenBitmap_Paint);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form2_MouseDown);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form2_MouseMove);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form2_MouseUp);
            ((System.ComponentModel.ISupportInitialize)(this.pic_Save)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pic_Exit)).EndInit();
            this.pan_Control.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox pic_Save;
        private System.Windows.Forms.PictureBox pic_Exit;
        private System.Windows.Forms.Panel pan_Control;
    }
}

1.1 Utility.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


/***********************************************************************************
 * 模块作者:Zheng
 * 创建时间:2023/11/16 14:31:29
 * 功能描述:
 * 
 * 使用说明:
 * 
 * 
 ************************************************************************************/

namespace ScreenShot
{
    public class Utility
    {
        public static Pen MPen = new Pen(Brushes.GreenYellow, 3);

        [DllImport("user32.dll")] //导入user32.dll函数库
        private static extern bool GetCursorPos(out Point lpPoint);//获取鼠标坐标

        /// 
        /// 获取屏幕图片
        /// 
        /// 相对于左上角的坐标
        /// 图片大小
        /// 截取到的图片
        public static Bitmap CopyScreenToImage(Point upperLeftSource, Size size)
        {
            // 创建一个bitmap对象并将其设置为屏幕大小
            var bitmap = new Bitmap(size.Width, size.Height);
            // 创建一个Graphics对象并将其设置为
            using (var g = Graphics.FromImage(bitmap))
            {
                // 将整个屏幕绘制到Graphics对象中
                g.CopyFromScreen(upperLeftSource, Point.Empty, size);
            }
            //string path = "1.bmp";
            //bitmap.Save(path, ImageFormat.Bmp);
            //Process.Start(path);
            // 将截图保存为jpg文件
            return bitmap;
        }

        /// 
        /// 获取全屏图片
        /// 
        /// 截取到的图片
        public static Bitmap CopyScreenToImage(out Rectangle _bitmapDrawRect)
        {
            //todo 
            _bitmapDrawRect = GetAllScreenRect();
            //_bitmapDrawRect = Screen.GetBounds(Point.Empty);
            return CopyScreenToImage(_bitmapDrawRect.Location, _bitmapDrawRect.Size);
        }

        /// 
        /// 获取所有屏幕的区域
        /// 
        /// 
        public static Rectangle GetAllScreenRect()
        {
            int xMin = 0;
            int yMin = 0;
            int xMax = 0;
            int yMax = 0;

            foreach (var screen in Screen.AllScreens)
            {
                xMin = Math.Min(xMin, screen.Bounds.X);
                yMin = Math.Min(yMin, screen.Bounds.Y);

                xMax = Math.Max(xMax, screen.Bounds.X + screen.Bounds.Width);
                yMax = Math.Max(yMax, screen.Bounds.Y + screen.Bounds.Height);
            }

            var rect = new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin);

            return rect;
        }

        /// 
        /// 获取鼠标在屏幕中的坐标
        /// 
        /// 
        public static Point GetMousePose()
        {
            Point mp = new Point();
            GetCursorPos(out mp);
            return mp;
        }

        /// 
        /// 绘制图像(按比例填充)
        /// 
        /// 绘画类
        /// 图像
        /// 承载图像的父控件大小
        public static void DrawImage(Graphics e, Bitmap bmp, SizeF size)
        {

            //父控件大小 和Bitmap 的宽高比
            var picByBmpScale = Math.Min(size.Width / bmp.Width, size.Height / bmp.Height);

            //1.图像位置大小
            var bmpPos = new RectangleF
            {
                Width = bmp.Width * picByBmpScale,
                Height = bmp.Height * picByBmpScale
            };
            bmpPos.X = (size.Width - bmpPos.Width) / 2;
            bmpPos.Y = (size.Height - bmpPos.Height) / 2;

            //2.图像绘制区域
            var drawArea = new RectangleF
            {
                X = 0,
                Y = 0,
                Width = bmp.Width,
                Height = bmp.Height
            };

            //绘制图像
            e.SmoothingMode = SmoothingMode.HighQuality;//指定抗锯齿的呈现
            e.DrawImage(bmp, bmpPos, drawArea, GraphicsUnit.Pixel);//绘制图像
        }

        /// 
        /// 根据两点绘制矩形
        /// 
        /// 
        /// 第一个点
        /// 第二个点
        public static void DrawRect(Graphics e, PointF firstPoint, PointF secondPoint)
        {
            var x1 = firstPoint.X;
            var y1 = firstPoint.Y;
            var x2 = secondPoint.X;
            var y2 = secondPoint.Y;
            if (x1 > x2)
            {
                x1 = x1 + x2;
                x2 = x1 - x2;
                x1 = x1 - x2;
            }
            if (y1 > y2)
            {
                y1 = y1 + y2;
                y2 = y1 - y2;
                y1 = y1 - y2;
            }

            e.DrawRectangle(MPen, x1, y1, x2 - x1, y2 - y1);
        }

        /// 
        /// 根据两点绘制(填充)矩形
        /// 
        /// 
        /// 第一个点
        /// 第二个点
        public static void DrawFillRect(Graphics e, PointF firstPoint, PointF secondPoint)
        {
            var x1 = firstPoint.X;
            var y1 = firstPoint.Y;
            var x2 = secondPoint.X;
            var y2 = secondPoint.Y;
            if (x1 > x2)
            {
                x1 = x1 + x2;
                x2 = x1 - x2;
                x1 = x1 - x2;
            }
            if (y1 > y2)
            {
                y1 = y1 + y2;
                y2 = y1 - y2;
                y1 = y1 - y2;
            }

            SolidBrush brushgreen = new SolidBrush(Color.DarkSlateGray);
            e.FillRectangle(brushgreen, x1, y1, x2 - x1, y2 - y1);
            e.DrawRectangle(MPen, x1, y1, x2 - x1, y2 - y1);
        }

        /// 
        /// 绘制有透明度的(填充)矩形
        /// 
        /// 
        /// 第一个点
        public static void DrawTransparencyFillRect(Graphics e, RectangleF rect)
        {
            Color customColor = Color.FromArgb(100, Color.Black);
            SolidBrush shadowBrush = new SolidBrush(customColor);
            e.FillRectangle(shadowBrush, rect);
            //e.DrawRectangles(MPen, new[] { rect });
        }

        /// 
        /// 绘制矩形
        /// 
        /// 
        /// 矩形区域
        public static void DrawRect(Graphics e, RectangleF rect)
        {
            e.DrawRectangles(MPen, new[] { rect });
        }

        /// 
        /// 绘制(填充)矩形
        /// 
        /// 
        /// 矩形区域
        public static void DrawFillRect(Graphics e, RectangleF rect)
        {
            SolidBrush brushgreen = new SolidBrush(MPen.Color);
            e.FillRectangle(brushgreen, rect);
        }

        /// 
        /// 在控件指定坐标点绘制文本
        /// 
        /// 
        /// 指定坐标点
        /// 文本字体
        /// 文本内容
        public static void DrawText(Graphics e, PointF point, Font font, string text)
        {
            SolidBrush Mbrushgreen = new SolidBrush(Color.Red);
            e.DrawString(text, font, Mbrushgreen, point);
        }


        /// 
        /// 获取图像指定区域
        /// 
        /// 相对于左上角的坐标
        /// 图片大小
        /// 截取到的图片
        public static Bitmap GetImageRect(Bitmap sourcebitmap, Rectangle rect)
        {
            // 创建一个bitmap对象
            var bitmap = new Bitmap(rect.Width, rect.Height);
            // 创建一个Graphics对象并将其设置为
            var g = Graphics.FromImage(bitmap);

            // 目标位置 
            var rect1 = new Rectangle(new Point(0, 0), rect.Size);
            // 原图位置 
            var rect2 = new Rectangle(new Point(rect.X, rect.Y), rect.Size);
            g.DrawImage(sourcebitmap, rect1, rect2, GraphicsUnit.Pixel);

            return bitmap;
        }
    }
}

你可能感兴趣的:(C#,C#绘图,Winform,c#,开发语言,windows)