0
\$\begingroup\$

I'm making a chess game with wpf and I have never used wpf before. I've used windows forms, so besides the xaml, it's pretty familiar. Usually when I want to create a mousedown event I look at what I have on window design screen->click the object->go to properties->events->MouseDown event->double click the event->it creates a method that executes when the mouse is pressed on that element. Looks like this...

private void Pawn_1__MouseDown(object sender, MouseButtonEventArgs e)
{

}

But for my chess game in my C# code in the mainwindow constructor I put some initialization code to place a bunch of rectangles all over the screen representing the grid I'd be using for my chess game. How can I create a MouseDown event for these rectangles since they aren't in the designer?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I am guessing you are using System.Draw methods to draw the rectangles (I hope you are not drawing labels or something cause that would kill performance). I would make a mouse down event on the form, and then use the mouse position value to get the rectangle that was clicked depending on the width/height of them.

So say the user clicks at 250,250 and the rectangles are 100x100, then he clicked the rectangle[(int) mouse.X / 100, (int) mouse.Y / 100], which is rectangle[2,2] (third row third column). That way you can access the clicked rectangle and handle it the way you are supposed to.

\$\endgroup\$
4
  • \$\begingroup\$ I have a Canvas set up and I just add them to the Canvas using canvasnamehere.children.Add(objhere); \$\endgroup\$ Feb 15, 2015 at 4:12
  • \$\begingroup\$ @AndrewWilson So I suppose my answer would work ? or you were looking for something else ? \$\endgroup\$
    – dimitris93
    Feb 15, 2015 at 4:13
  • \$\begingroup\$ Yeah, I don't know why I didn't think of that. -.- \$\endgroup\$ Feb 15, 2015 at 4:26
  • \$\begingroup\$ @AndrewWilson you could use this logic for any shape as well, using a list of shapes, setting each shape's properties and using the proper geometry. here the position of the rectangle is granted because it is a chess game and each rectangle is strictly next to each other, but you get the idea \$\endgroup\$
    – dimitris93
    Feb 15, 2015 at 4:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .