c# 实现框选截图功能
时间: 2023-07-14 10:13:03 浏览: 200
以下是 C# 实现框选截图功能的代码示例:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class ScreenCapture : Form
{
private Point start;
private Rectangle rect;
public ScreenCapture()
{
this.DoubleBuffered = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
this.Cursor = Cursors.Cross;
this.MouseDown += ScreenCapture_MouseDown;
this.MouseMove += ScreenCapture_MouseMove;
this.MouseUp += ScreenCapture_MouseUp;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
private void ScreenCapture_MouseDown(object sender, MouseEventArgs e)
{
start = new Point(e.X, e.Y);
rect = new Rectangle(start, Size.Empty);
}
private void ScreenCapture_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point current = new Point(e.X, e.Y);
rect.Location = new Point(
Math.Min(start.X, current.X),
Math.Min(start.Y, current.Y));
rect.Size = new Size(
Math.Abs(start.X - current.X),
Math.Abs(start.Y - current.Y));
Invalidate();
}
}
private void ScreenCapture_MouseUp(object sender, MouseEventArgs e)
{
if (rect.Width > 0 && rect.Height > 0)
{
using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(rect.Location, Point.Empty, rect.Size);
}
Clipboard.SetImage(bitmap);
MessageBox.Show("截图已复制到剪贴板。");
}
}
Close();
}
public static void Main()
{
Application.Run(new ScreenCapture());
}
}
```
这个程序创建了一个全屏的窗体,并在窗体上绘制了一个红色的矩形,用于框选截图。当用户按下鼠标左键并拖动时,矩形会跟随鼠标移动。当用户释放鼠标左键时,程序会将框选区域的屏幕截图复制到剪贴板,并关闭窗体。
阅读全文