c# 鼠标框选 截屏
时间: 2023-08-02 22:19:18 浏览: 229
在C#中,可以使用以下代码实现鼠标框选截屏功能:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public static class ScreenShot
{
public static void TakeScreenShot(Rectangle rect, string fileName)
{
// 创建一个与指定矩形大小相同的图像
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height))
{
// 将指定矩形区域的屏幕图像拷贝到位图中
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(rect.Location, new Point(0, 0), rect.Size);
}
// 保存图像到文件
bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
public class ScreenShotForm : Form
{
private Point _startPoint;
private Rectangle _rect;
private bool _isDrawing;
public ScreenShotForm()
{
// 设置窗口样式
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
Cursor = Cursors.Cross;
// 注册鼠标事件
MouseDown += ScreenShotForm_MouseDown;
MouseMove += ScreenShotForm_MouseMove;
MouseUp += ScreenShotForm_MouseUp;
}
private void ScreenShotForm_MouseDown(object sender, MouseEventArgs e)
{
// 记录鼠标按下时的位置
_startPoint = e.Location;
_isDrawing = true;
}
private void ScreenShotForm_MouseMove(object sender, MouseEventArgs e)
{
if (_isDrawing)
{
// 计算框选矩形的位置和大小
int x = Math.Min(_startPoint.X, e.X);
int y = Math.Min(_startPoint.Y, e.Y);
int width = Math.Abs(_startPoint.X - e.X);
int height = Math.Abs(_startPoint.Y - e.Y);
_rect = new Rectangle(x, y, width, height);
// 重绘窗口
Invalidate();
}
}
private void ScreenShotForm_MouseUp(object sender, MouseEventArgs e)
{
if (_isDrawing)
{
// 停止框选并保存截图
_isDrawing = false;
ScreenShot.TakeScreenShot(_rect, "screenshot.png");
// 关闭窗口
Close();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (_isDrawing)
{
// 绘制框选矩形
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, _rect);
}
}
}
}
```
使用时,可以创建一个 `ScreenShotForm` 实例,它会全屏显示并允许鼠标框选截图:
```csharp
Application.Run(new ScreenShotForm());
```
阅读全文