我有一些代码在Canvas
上绘制矩形。这一切都很有效,但是,当鼠标离开Canvas
的边界时,矩形的绘图会冻结而没有任何反应。一些代码
<Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" />
private Point startPoint;
private Rectangle rect;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(rect,startPoint.X);
Canvas.SetTop(rect,startPoint.X);
canvas.Children.Add(rect);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Released || rect == null)
return;
var pos = e.GetPosition(canvas);
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
rect = null;
}
我想要的是绘制到矩形继续,即使我走出Canvas
的边界,但显然矩形的尺寸被剪切到{{1}的边界}。
实现这一目标的最佳方法是什么?
答案 0 :(得分:2)
您应该在MouseDown处理程序中捕获鼠标
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
canvas.CaptureMouse();
...
}
并在MouseUp处理程序中释放捕获
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
...
canvas.ReleaseMouseCapture();
}