public partial class MainWindow : Window
{
private Rectangle rectangle;
private Point clickLocation;
public MainWindow()
{
InitializeComponent();
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
this.Close();
}
}
private Rectangle CreateRectangle()
{
var rect = new Rectangle();
rect.Stroke = Brushes.White;
rect.StrokeThickness = 2;
return rect;
}
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
rectangle = this.CreateRectangle();
clickLocation = e.GetPosition(canvas);
Canvas.SetLeft(rectangle, clickLocation.X);
Canvas.SetTop(rectangle, clickLocation.Y);
rectangle.Width = 0;
rectangle.Height = 0;
canvas.Children.Add(rectangle);
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (rectangle == null) return;
var location = e.GetPosition(canvas);
var width = location.X - clickLocation.X;
var height = location.Y - clickLocation.Y;
if (width < 0)
{
Canvas.SetLeft(rectangle, location.X);
width = -width;
}
if (height < 0)
{
Canvas.SetTop(rectangle, location.Y);
height = -height;
}
rectangle.Width = width;
rectangle.Height = height;
}
private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var rect = new Rect();
rect.X = Canvas.GetLeft(rectangle);
rect.Y = Canvas.GetTop(rectangle);
rect.Width = rectangle.Width;
rect.Height = rectangle.Height;
this.HandleScreenGrab(rect);
canvas.Children.Clear();
rectangle = null;
}
private void HandleScreenGrab(Rect region)
{
//...
}
}