gpt4 book ai didi

c# - 鼠标点击 Canvas 中的对象

转载 作者:行者123 更新时间:2023-12-02 22:05:48 24 4
gpt4 key购买 nike

我有一个简单的应用程序,可以绘制椭圆、直线和矩形。

代码:

 private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);

if(figura == "linia")
{
linia = new Line
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};

canvas.Children.Add(linia);
}

if (figura == "kwadrat")
{
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};

Canvas.SetLeft(rect, startPoint.X);
Canvas.SetTop(rect, startPoint.X);

canvas.Children.Add(rect);
}

else if (figura == "kolko")
{
circ = new Ellipse
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};

Canvas.SetLeft(circ, startPoint.X);
Canvas.SetTop(circ, startPoint.X);

canvas.Children.Add(circ);
}
}

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released || rect == null && circ == null && linia == 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;

if(figura == "linia")
{
linia.X1 = startPoint.X;
linia.Y1 = startPoint.Y;
linia.X2 = pos.X;
linia.Y2 = pos.Y;
}

if (figura == "kwadrat")
{
rect.Width = w;
rect.Height = h;

Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}

if (figura == "kolko")
{
circ.Width = w;
circ.Height = h;

Canvas.SetLeft(circ, x);
Canvas.SetTop(circ, y);
}
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
rect = null;
circ = null;
}

现在我想对对象做一些事情,比如调整大小、移动等。当它们被鼠标点击时。我不知道如何找到被鼠标点击的对象。你能帮帮我吗?

最佳答案

e.OriginalSource将使您获得实际单击的控件。

关于c# - 鼠标点击 Canvas 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16151459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com