I am trying to generate random points on the canvas. So i want to the random point on the screen to move to a new random location, when mouse touches it. How do i do this?? this is not happening with any of the mouse events. An example would be appreciated.
Asked
Active
Viewed 1,342 times
1
-
5at what stage you fail? can show some code, please? – Tigran Apr 14 '12 at 21:17
-
well i am trying to work with this code http://stackoverflow.com/questions/3643639/move-a-rectangle-around-a-canvas but i want to change the position of the rectangle to a new random position when mouse approaches it or touches it – user1221876 Apr 14 '12 at 21:19
-
You need to read the position once in a while, e.g. see [link](http://stackoverflow.com/questions/1316681/getting-mouse-position-in-c-sharp) – Casperah Apr 14 '12 at 21:33
1 Answers
1
Well you can attach MouseMove event with rectangle and handle the random positioning of rectangle in this event.
Updated Referring to the answer in this link - Move a rectangle around a canvas. You need to update Add Click event in this way -
private void Add_Click(object sender, RoutedEventArgs e)
{
Point newPoint;
Rectangle rectangle;
newPoint = GetRandomPoint();
rectangle = new Rectangle {Width = 4, Height = 4, Fill = Brushes.Red};
rectangle.MouseMove += new MouseEventHandler(rectangle_MouseMove);
m_Points.Add(newPoint);
PointCanvas.Children.Add(rectangle);
Canvas.SetTop(rectangle,newPoint.Y);
Canvas.SetLeft(rectangle,newPoint.X);
}
void rectangle_MouseMove(object sender, MouseEventArgs e)
{
Rectangle rectangle = sender as Rectangle;
Point newPoint;
newPoint = GetRandomPoint();
Canvas.SetTop(rectangle, newPoint.Y);
Canvas.SetLeft(rectangle, newPoint.X);
}
I have attached the MouseMove event with rectangle when we create it and then moving the rectangle randomly in this event. Hope this helps you!!

Community
- 1
- 1

user1246682
- 206
- 2
- 7