Pajkec
Pajkec

Reputation: 67

get name of element under mouse cursor on mouse click

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!

Upvotes: 2

Views: 4211

Answers (2)

Clemens
Clemens

Reputation: 128097

Use the OriginalSource property of the MouseButtonEventArgs:

var element = e.OriginalSource as FrameworkElement;
var name = element?.Name;

Upvotes: 3

Lupu Silviu
Lupu Silviu

Reputation: 1165

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

Upvotes: 0

Related Questions