Cody
Cody

Reputation: 53

How can I listen for left mouseclicks on a canvas in a C# WPF?

I am trying to listen for a mouse click anywhere on my window (Except for the locations where the buttons are, but I'll deal with that later) and then return the point (x,y) of the location.

here is the relevant code:

 private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Console.WriteLine("mouseLeft is clicked");
    Point x = e.MouseDevice.GetPosition(this);
    Console.WriteLine(x.X);
    Console.WriteLine(x.Y);
}

<Canvas MouseLeftButtonDown="Grid_MouseLeftButtonDown">

When I click, nothing is printed. What am I doing wrong exactly? The first method is inside mainWindow.Xaml.cs.

thanks in advance.

Upvotes: 3

Views: 3920

Answers (2)

hein
hein

Reputation: 51

Set background to transparent and set size of canvas!

Upvotes: 5

scmccart
scmccart

Reputation: 1169

Sometimes things won't be written to the console correctly in GUI Apps, try using Debug.WriteLine, MessageBox.Show, or settings a breakpoint to see if the event is being fired.

The code you have there looks perfectly fine.

Upvotes: 3

Related Questions