get name of element under mouse cursor on mouse click

3.9k Views Asked by At

I am trying to make a method where i can get the element that was clicked. In App.xaml.cs i have method OnPreviewMouseDown that is activated for each click in application.

Now i need some help with getting element name from sender (if this is even possible)

 static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.RightButton == MouseButtonState.Pressed)
        {
            Control control = (Control)sender;   // Sender gives you which control is clicked.
            string name = control.Name.ToString();  //returns main window name, not element....

            string typee = sender.GetType().ToString();  //returns PPPMain.Views.MainWindow

        }
    }

I tried this and some other suggestions from internet but didn't find any solutions...

Thanks in advance!

2

There are 2 best solutions below

0
Clemens On BEST ANSWER

Use the OriginalSource property of the MouseButtonEventArgs:

var element = e.OriginalSource as FrameworkElement;
var name = element?.Name;
0
Lupu Silviu On

You could try using this code inside your event:

VisualTreeHelper.HitTest(this, e.GetPosition(this));

you can find more in this other topic: WPF Get Element(s) under mouse