当前位置: 首页 > news >正文

c#使用forms实现屏幕截图

说明:
c#使用forms实现屏幕截图
step1: 点击按钮,拖拽,截图,保存本地
C:\Users\wangrusheng\RiderProjects\WinFormsApp1\WinFormsApp1\Form1.cs

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

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

            // 添加Label控件
            Label label = new Label();
            label.Text = "拖拽选择区域截图";
            label.AutoSize = true;
            label.Location = new Point(20, 20);
            this.Controls.Add(label);

            // 添加截图按钮
            Button screenshotButton = new Button();
            screenshotButton.Text = "开始截图";
            screenshotButton.Location = new Point(20, 50);
            screenshotButton.Click += ScreenshotButton_Click;
            this.Controls.Add(screenshotButton);
        }

        private void ScreenshotButton_Click(object sender, EventArgs e)
        {
            this.Hide();
            using (var selector = new RegionSelector())
            {
                if (selector.ShowDialog() == DialogResult.OK)
                {
                    SaveScreenshot(selector.SelectedRegion);
                }
            }
            this.Show();
        }

        private void SaveScreenshot(Rectangle region)
        {
            using (Bitmap bmp = new Bitmap(region.Width, region.Height))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.CopyFromScreen(region.Location, Point.Empty, region.Size);
                }

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "PNG 图片|*.png|JPEG 图片|*.jpg";
                sfd.Title = "保存截图";
                
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    ImageFormat format = sfd.FilterIndex switch
                    {
                        1 => ImageFormat.Png,
                        2 => ImageFormat.Jpeg,
                        _ => ImageFormat.Png
                    };
                    bmp.Save(sfd.FileName, format);
                    MessageBox.Show($"截图已保存至:{sfd.FileName}", "操作成功");
                }
            }
        }
    }

    public class RegionSelector : Form
    {
        private Point start;
        private Rectangle selection;
        private bool selecting;

        public Rectangle SelectedRegion => selection;

        public RegionSelector()
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            this.Opacity = 0.3;
            this.DoubleBuffered = true;
            this.TopMost = true;
            this.Cursor = Cursors.Cross;
            this.BackColor = Color.Black;
            this.MouseDown += (s, e) => StartSelection(e);
            this.MouseMove += (s, e) => UpdateSelection(e);
            this.MouseUp += (s, e) => EndSelection();
            this.KeyDown += (s, e) => { if (e.KeyCode == Keys.Escape) CancelSelection(); };
        }

        private void StartSelection(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                start = Control.MousePosition;
                selecting = true;
            }
        }

        private void UpdateSelection(MouseEventArgs e)
        {
            if (selecting)
            {
                Point current = Control.MousePosition;
                selection = new Rectangle(
                    Math.Min(start.X, current.X),
                    Math.Min(start.Y, current.Y),
                    Math.Abs(start.X - current.X),
                    Math.Abs(start.Y - current.Y));
                Invalidate();
            }
        }

        private void EndSelection()
        {
            if (selection.Width > 0 && selection.Height > 0)
            {
                DialogResult = DialogResult.OK;
            }
            Close();
        }

        private void CancelSelection()
        {
            selection = Rectangle.Empty;
            Close();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (selecting && !selection.IsEmpty)
            {
                Rectangle screenRect = RectangleToClient(RectangleToScreen(selection));
                using (Pen pen = new Pen(Color.Red, 2))
                {
                    e.Graphics.DrawRectangle(pen, screenRect);
                }
            }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            Cursor.Current = Cursors.Default;
        }
    }
}

step2:简单截取整个屏幕 C:\Users\wangrusheng\RiderProjects\WinFormsApp1\WinFormsApp1\Form1.cs

using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace WinFormsApp1;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // 添加Label控件
        Label label = new Label();
        label.Text = "Hello World!";
        label.AutoSize = true;
        label.Location = new Point(20, 20);
        this.Controls.Add(label);

        // 添加截图按钮
        Button screenshotButton = new Button();
        screenshotButton.Text = "截图";
        screenshotButton.Location = new Point(20, 50);
        screenshotButton.Click += ScreenshotButton_Click; // 绑定点击事件
        this.Controls.Add(screenshotButton);
    }

    private void ScreenshotButton_Click(object sender, EventArgs e)
    {
        // 获取主屏幕的尺寸
        Rectangle screenSize = Screen.PrimaryScreen.Bounds;
        
        // 创建位图对象
        using (Bitmap screenshot = new Bitmap(screenSize.Width, screenSize.Height))
        {
            // 使用Graphics对象捕获屏幕
            using (Graphics graphics = Graphics.FromImage(screenshot))
            {
                graphics.CopyFromScreen(Point.Empty, Point.Empty, screenSize.Size);
            }

            // 显示保存文件对话框
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "PNG 图片|*.png|JPEG 图片|*.jpg";
            saveDialog.Title = "保存截图";
            
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                // 根据用户选择的格式保存
                ImageFormat format = saveDialog.FilterIndex switch
                {
                    1 => ImageFormat.Png,
                    2 => ImageFormat.Jpeg,
                    _ => ImageFormat.Png
                };
                
                screenshot.Save(saveDialog.FileName, format);
                MessageBox.Show($"截图已保存至:{saveDialog.FileName}", "操作成功");
            }
        }
    }
}

end

相关文章:

  • 在MFC中使用Qt(六):深入了解QMfcApp
  • flutter框架中文文档,android智能手机编程答案
  • 第十一章 VGA显示图片(还不会)
  • pod之间访问不通怎么排查?
  • 音视频开发---常用工具
  • JAVASE(十二)常用类(一)Object类
  • 【STM32】GPIO输入(按键)
  • 如何实现高性能的在线 PDF 预览
  • 【新人系列】Golang 入门(十):错误处理详解 - 上
  • 广东新政激发产业活力,凡拓数创以全场景AI3D方案领跑机器人赛道
  • JAVA并发编程高级-线程安全集合-CopyOnWriteArrayList
  • 配置防火墙和SELinux(1)
  • 第二次作业
  • SpringAI 集成本地Ollama大模型
  • 2025年智慧能源与控制工程国际学术会议(SECE 2025)
  • 25大唐杯赛道一本科B组知识点大纲(下)
  • 基于OpenCV+MediaPipe手部追踪
  • Oracle数据库数据编程SQL<3.4 PL/SQL 自定义函数(Function)>
  • AI Agent开发大全第十六课-本地DeepSeek调用与官网DeepSeek调用stream流模式区别对待的全代码讲解
  • C语言中将整数转化为字符串的几种方法
  • 肥西网站推广公司/有做网站的吗
  • 网站建设佰首选金手指四/关键字优化用什么系统
  • 美食网站建设策划书/网站建设案例
  • 深圳市明日卓越科技有限公司做网站号码/营业推广怎么写
  • 北辰正方建设集团有限公司官方网站/怎么搭建属于自己的网站
  • 日本做的视频网站有哪些问题吗/做网站推广公司