Я работаю над созданием приложения для захвата экрана на C# с использованием WPF, где пользователь может нарисовать прямоугольник на экране, а приложение захватывает содержимое за этим прямоугольником — аналогично инструменту «Ножницы» Windows.Сейчас я зациклился на том, как преобразовать координаты нарисованного прямоугольника в координаты экрана. Вот код, который у меня есть:
using System;
using System.Drawing; // For screen capturing (Bitmap, Graphics)
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace ScreenCapture
{
public partial class MainWindow : Window
{
private System.Windows.Shapes.Rectangle DragRectangle = null; // Specify WPF Rectangle
private System.Windows.Point StartPoint, LastPoint;
public MainWindow()
{
InitializeComponent();
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape) { this.Close(); e.Handled = true; }
}
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
StartPoint = Mouse.GetPosition(canvas);
LastPoint = StartPoint;
// Initialize and style the rectangle
DragRectangle = new System.Windows.Shapes.Rectangle
{
Width = 1,
Height = 1,
Stroke = System.Windows.Media.Brushes.Red,
StrokeThickness = 1,
Cursor = Cursors.Cross
};
// Add the rectangle to the canvas
canvas.Children.Add(DragRectangle);
Canvas.SetLeft(DragRectangle, StartPoint.X);
Canvas.SetTop(DragRectangle, StartPoint.Y);
// Attach the mouse move and mouse up events
canvas.MouseMove += canvas_MouseMove;
canvas.MouseUp += canvas_MouseUp;
canvas.CaptureMouse();
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (DragRectangle == null) return;
// Update LastPoint to current mouse position
LastPoint = Mouse.GetPosition(canvas);
// Update rectangle dimensions and position
DragRectangle.Width = Math.Abs(LastPoint.X - StartPoint.X);
DragRectangle.Height = Math.Abs(LastPoint.Y - StartPoint.Y);
Canvas.SetLeft(DragRectangle, Math.Min(LastPoint.X, StartPoint.X));
Canvas.SetTop(DragRectangle, Math.Min(LastPoint.Y, StartPoint.Y));
}
private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
if (DragRectangle == null) return;
// Release mouse capture and remove event handlers
canvas.ReleaseMouseCapture();
//canvas.MouseMove -= canvas_MouseMove;
//canvas.MouseUp -= canvas_MouseUp;
// Get coordinates for the capture area
int x = (int)Math.Min(LastPoint.X, StartPoint.X);
int y = (int)Math.Min(LastPoint.Y, StartPoint.Y);
int width = (int)Math.Abs(LastPoint.X - StartPoint.X);
int height = (int)Math.Abs(LastPoint.Y - StartPoint.Y);
// Ensure dimensions are valid before capture
if (width > 0 && height > 0)
{
CaptureScreen(x, y, width, height);
}
//// Clean up: remove rectangle from canvas
//canvas.Children.Remove(DragRectangle);
//DragRectangle = null;
this.Close();
}
private void CaptureScreen(int x, int y, int width, int height)
{
// Convert WPF coordinates to screen coordinates
var screenLeft = (int)(PointToScreen(new System.Windows.Point(x, y)).X);
var screenTop = (int)(PointToScreen(new System.Windows.Point(x, y)).Y);
using (Bitmap bitmap = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
// Capture the area of the screen based on converted coordinates
g.CopyFromScreen(screenLeft, screenTop, 0, 0, new System.Drawing.Size(width, height));
}
// Save the captured image to the desktop
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = System.IO.Path.Combine(desktopPath, $"Screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png");
bitmap.Save(filePath);
MessageBox.Show($"Screenshot saved to {filePath}");
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... for-screen
C# WPF: перевод координат прямоугольника в координаты экрана для захвата экрана ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
C# WPF: перевод координат прямоугольника в координаты экрана для захвата экрана
Anonymous » » в форуме C# - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-