How to know what control the mouse has clicked in

2019-08-17 16:17发布

I am creating a C# WPF application and looking for a way to do the following:

I have a canvas with different user controls in it and a button.

When I click on the button the cursor change to a hand (Canvas.Cursor = Cursors.Hand)

Then if I click on one of the controls I get a message box showing the name of the control clicked (the name is a public property of the control).

If I click somewhere else i the cursor resets and I should click on the button again before I can get the name again.

I tried playing with events and handlers but couldn't achieve what I wanted.

Thank you very much for you help

1条回答
Viruses.
2楼-- · 2019-08-17 16:57

You can use Canvas.MouseDown and use VisualTreeHelper.HitTest() with GetPosition() of the mouse down event args to get the element that was clicked.

<Canvas Name="myCanvas" MouseDown="MouseDownHandler" />

public void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
    HitTestResult target = VisualTreeHelper.HitTest(myCanvas, e.GetPosition(myCanvas));

    while(!(target is Control) && (target != null))
    {
        target = VisualTreeHelper.GetParent(target);
    }
    // now if target is not null, it's the control that was clicked...
}

Then you can use VisualTreeHelper.GetParent() (in a while loop) to get the control that was clicked.

查看更多
登录 后发表回答