Search code examples
c#wpf

Set UI Element Position to Mouse Position


I wrote a little Program that should display a Ellipse at the exact mouse position. The Problem is that, the way Iam doing it right now , The Mouse and Ellipse Position are only exact at the center of the Screen. If I put the mouse further away to the windowborder they drift further and further away.

I use the MouseOver Element to Update the Mouse Position.

enter image description here

Here is my code:

private void Window_MouseMove(object sender, MouseEventArgs e)
{
   Main_Grid.Children.Clear();

   MousePos_Ellipse = new Ellipse();
   Point MousePos_Point = new Point();

   MousePos_Point = Mouse.GetPosition(Main_Grid);

   Main_Grid.Children.Remove(MousePos_Ellipse);

   SolidColorBrush mySolidColorBrush = new SolidColorBrush();


   mySolidColorBrush.Color = Color.FromArgb(55, 255, 255, 0);
   MousePos_Ellipse.Fill = mySolidColorBrush;
   MousePos_Ellipse.StrokeThickness = 2;
   MousePos_Ellipse.Stroke = Brushes.Black;

   // Set the width and height of the Ellipse.
   MousePos_Ellipse.Width = 15;
   MousePos_Ellipse.Height = 15;
   // At this Point I do my Positioning
   MousePos_Ellipse.Margin = new Thickness(left: MousePos_Point.X - ( Main_Grid.ActualWidth / 2)  , top: MousePos_Point.Y - ( Main_Grid.ActualHeight / 2 ), right: 0 , bottom: 0);

    // Add the Ellipse to the Grid
    Main_Grid.Children.Add(MousePos_Ellipse);
}

Solution

  • I propose to use a Canvas instead of a grid.

    With a canvas you can simply set the ellipse position like that:

       Canvas.SetLeft(MousePos_Ellipse, MousePos_Point.X);
       Canvas.SetTop(MousePos_Ellipse, MousePos_Point.Y);
    

    The Grid control will do automatic positioning and sizing of child elements and is therefore not so suitable for your goal.