Reputation: 8118
I'm trying to draw a circle and a rectangle when the mouse is clicked so I got the x and y cords of the mouse click.
I've searched on the internet that in C# this can only be done with Margin, there is no origin or something like in java, you could give x and y to the constructor.
Now I'm trying to set this right but I can't figure out how to calculate this properly:
According to this:
http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin%28v=vs.95%29.aspx
rec.Margin = new Thickness(0, 0,0, 0);
Can someone help me? Or is it not possible with this?
Upvotes: 0
Views: 1823
Reputation: 8118
void MyCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
Point ClickPoint = e.GetPosition(MyCanvas);
Rectangle Rectangle = new Rectangle();
System.Windows.Controls.Canvas.SetTop(Rectangle, ClickPoint.Y)
System.Windows.Controls.Canvas.SetLeft(Rectangle, ClickPoint.X)
MyCanvas.Children.Add(Rectangle);
}
Thanks to spencer.
Upvotes: 0
Reputation: 35107
Is this WPF or Windows Forms? WPF mouse event args have a GetPosition(UIElement)
method which will tell you the mouse coordinates relative to the control you pass in. So if you're trying to draw a rectangle on a System.Windows.Controls.Canvas
called MyCanvas
you can use the Point
returned by e.GetPosition(MyCanvas)
to place your rectangle.
Here's an example:
void MyCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
Point ClickPoint = e.GetPosition(MyCanvas);
Rectangle Rectangle = new Rectangle();
System.Windows.Controls.Canvas.SetTop(Rectangle, ClickPoint.Y)
System.Windows.Controls.Canvas.SetLeft(Rectangle, ClickPoint.X)
MyCanvas.Children.Add(Rectangle);
}
Upvotes: 1