C#winform实现截取屏幕图片,并进行拉伸、移动

解决方案

  1. 通过创建一个透明的Form窗体
  2. 检测鼠标按下(MouseDown)、抬起(MouseMove)、移动(MouseUp)事件
  3. 添加窗体右键事件(截图完成后方便显示可操作的功能)
  4. 准备一个图片展示控件(PictureBox)
  5. 具体做法
    1.鼠标按下时将PictureBox定位到鼠标按下的坐标(Cursor.Position)
    2.鼠标按下移动时计算PictureBox的坐标与鼠标的坐标从而改变PictureBox的大小(Size)
    3.鼠标抬起时绘制图片 并 显示右键菜单

效果展示

使用代码的效果图

解决问题

  • 下面代码中
  1. ScreenshotForm是创建的Form窗体,没有添加任何控件
  2. ScaleMoveControl通过右侧超链接查看控制控件的缩放、移动 的类
  • ScreenHelper过右侧超链接查看屏幕帮助类
  • 代码需要自行做一些相应修改才可使用,诸位拿到代码后问题想做修改问题应该大不
		/// <summary>
    /// 截图窗体
    /// </summary>
    public partial class ScreenshotForm : Form
    {
        /// <summary>
        /// 实例化
        /// </summary>
        public ScreenshotForm()
        {
            InitializeComponent();

            this.FormBorderStyle = FormBorderStyle.None;
            //this.ControlBox = false;
            //this.ShowInTaskbar = false;
            //this.ShowIcon = false;
            this.TopMost = true;
            this.Opacity = 0.5;
            this.BackColor = Color.Black;
            this.WindowState = FormWindowState.Maximized;
            AddContextMenuStrip();
            AddMouseScreenshotClick();
        }

        #region 自定义属性、事件
        /// <summary>
        /// 点击截图完成后会产生的图片 (图片大小≥1存在)
        /// </summary>
        /// <remarks>
        /// 可通过 DialogResult = DialogResult.OK 来判断该值是否有效
        /// </remarks>
        public System.Drawing.Bitmap Bitmap { get; private set; }

        /// <summary>
        /// 截图时相对于左上角的坐标 (图片大小≥1存在)
        /// </summary>
        /// <remarks>
        /// 可通过 DialogResult = DialogResult.OK 来判断该值是否有效
        /// </remarks>
        public System.Drawing.Point UpperLeftSource { get; private set; }

        /// <summary>
        /// 点击 完成 时触发事件
        /// </summary>
        public event Action ClickSuccessEvent;

        /// <summary>
        /// 点击 退出 时触发事件
        /// </summary>
        public event Action ClickExitEvent;
        #endregion

        #region 添加右键菜单
        /// <summary>
        /// 添加右键菜单
        /// </summary>
        private void AddContextMenuStrip()
        {
            this.ContextMenuStrip = new ContextMenuStrip();
            this.ContextMenuStrip.Items.Add(new ToolStripMenuItem("操作图片(双击图片完成操作)", null, (sender, e) =>
            {
                ClearImage();
                //pictureBox.Refresh();
                pictureBox.BorderStyle = BorderStyle.FixedSingle;
                scaleMoveControl.IsCanOperate = true;
            }));
            this.ContextMenuStrip.Items.Add(new ToolStripMenuItem("保存", null, (sender, e) =>
            {
                var bitmap = GetBitmap();
                if (bitmap == null)
                {
                    return;
                }
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "图片|*.jpg;*.jpeg;*.png;";
                saveFileDialog.DefaultExt = ".jpg";
                saveFileDialog.AddExtension = true;
                var Result = saveFileDialog.ShowDialog();
                if (!Result.Equals(DialogResult.OK))
                {
                    return;
                }
                var fileName = saveFileDialog.FileName;
                var path = System.IO.Path.GetDirectoryName(fileName);
                System.IO.Directory.CreateDirectory(path);
                var Extension = System.IO.Path.GetExtension(path);
                if (Extension.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || Extension.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase))
                {
                    bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else if (Extension.Equals(".png", StringComparison.CurrentCultureIgnoreCase))
                {
                    bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    bitmap.Save(fileName);
                }
            }));
            this.ContextMenuStrip.Items.Add(new ToolStripMenuItem("完成(图片复制到剪切板)", null, (sender, e) =>
            {
                var bitmap = GetBitmap();
                if (bitmap != null)
                {
                    Clipboard.Clear();
                    Clipboard.SetImage(bitmap);
                }

                if (ClickSuccessEvent != null)
                {
                    ClickSuccessEvent();
                }
            }));
            this.ContextMenuStrip.Items.Add(new ToolStripMenuItem("退出", null, (sender, e) =>
            {
                this.Close();
                if (ClickExitEvent != null)
                {
                    ClickExitEvent();
                }
            }));
        }
        #endregion

        #region 设置鼠标点击事件
        /// <summary>
        /// 展示图片用
        /// </summary>
        PictureBox pictureBox = new PictureBox();

        /// <summary>
        /// 控制控件的缩放、移动
        /// </summary>
        ScaleMoveControl scaleMoveControl { get; set; }
        /// <summary>
        /// 屏幕截图点击事件
        /// </summary>
        private void AddMouseScreenshotClick()
        {
            #region 截图代码(原始版本已注释)
            //var Location = mouseEvent.Location;
            //var Position = Cursor.Position;

            //Rectangle bounds = Screen.GetBounds(Point.Empty);
             创建一个bitmap对象并将其设置为屏幕大小
            //using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            //{
            //    // 创建一个Graphics对象并将其设置为
            //    using (Graphics g = Graphics.FromImage(bitmap))
            //    {
            //        // 将整个屏幕绘制到Graphics对象中
            //        g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
            //    }
            //    // 将截图保存为jpg文件
            //    bitmap.Save("123.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            //}
            #endregion

            pictureBox.Visible = true;
            this.Controls.Add(pictureBox);
            
            //绑定鼠标按下事件
            this.MouseDown += ScreenshotForm_MouseDown;
            pictureBox.MouseDown += ScreenshotForm_MouseDown;

            //绑定鼠标移动事件
            this.MouseMove += (sender, e) =>
            {
                if (scaleMoveControl.IsCanOperate)
                {
                    return;
                }
                if (!e.Button.Equals(MouseButtons.Left))
                {
                    return;
                }

                var MouseMovePosition = Cursor.Position;
                var size = new System.Drawing.Size(Math.Abs(MouseMovePosition.X - pictureBox.Location.X), Math.Abs(MouseMovePosition.Y - pictureBox.Location.Y));
                if (size.Width <= 0 || size.Height <= 0)
                {
                    return;
                }
                pictureBox.Size = size;
            };

            //绑定鼠标抬起事件
            this.MouseUp += (sender, e) =>
            {
                if (scaleMoveControl.IsCanOperate)
                {
                    return;
                }
                if (!e.Button.Equals(MouseButtons.Left))
                {
                    return;
                }
                var MouseUpPosition = Cursor.Position;

                RefreshImage();
                //pictureBox.SuspendLayout();
                this.ContextMenuStrip.Show(MouseUpPosition);
            };

            scaleMoveControl = new ScaleMoveControl(pictureBox);
            scaleMoveControl.IsCanOperate = false;
            
            pictureBox.DoubleClick += (sender, e) =>
            {
                scaleMoveControl.IsCanOperate = false;
                RefreshImage();
                this.ContextMenuStrip.Show(Cursor.Position);
            };
        }

        /// <summary>
        /// 鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScreenshotForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (scaleMoveControl.IsCanOperate)
            {
                return;
            }
            if (!e.Button.Equals(MouseButtons.Left))
            {
                return;
            }
            ClearImage();
            pictureBox.Size = System.Drawing.Size.Empty;
            pictureBox.Location = Cursor.Position;
            pictureBox.BorderStyle = BorderStyle.FixedSingle;
            //pictureBox.ResumeLayout(false);
        }

        /// <summary>
        /// 对图片控件绘制图片
        /// </summary>
        private void RefreshImage()
        {
            if (pictureBox.Width <= 0 || pictureBox.Height <= 0)
            {
                ClearImage();
                return;
            }
            pictureBox.Refresh();
            var Size = pictureBox.Size;
            pictureBox.Image = ScreenHelper.CopyScreenToImage(pictureBox.Location, Size);
            pictureBox.BorderStyle = BorderStyle.None;
        }

        /// <summary>
        /// 清除图片
        /// </summary>
        private void ClearImage()
        {
            if (pictureBox.Image != null)
            {
                pictureBox.Image.Dispose();
                pictureBox.Image = null;
            }
        }
        #endregion

        #region 拿到当前截取的图片
        /// <summary>
        /// 拿到当前截取的图片
        /// </summary>
        /// <returns>null表示截图区域不存在</returns>
        protected System.Drawing.Bitmap GetBitmap()
        {
            this.Close();
            if (pictureBox.Image != null && !pictureBox.Size.Equals(System.Drawing.Size.Empty))
            {
                var bitmap = ScreenHelper.CopyScreenToImage(pictureBox.Location, pictureBox.Size);
                this.Bitmap = bitmap;
                this.UpperLeftSource = pictureBox.Location;
                this.DialogResult = DialogResult.OK;
                return bitmap;
            }
            return null;
        }
        #endregion

        /// <summary>
        /// 弹出截图窗体
        /// </summary>
        /// <returns></returns>
        public static ScreenshotForm ShowForm()
        {
            ScreenshotForm screenshotForm = new ScreenshotForm();
            screenshotForm.Show();
            return screenshotForm;
        }
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值