Search code examples
gdi

How to detect if my mouse position is within a rectangle c#?


I am trying to write an application to draw schematic diagrams which contain rectangles, lines and circles. Now I want to add another functionality to drag a rectangle to different position. The problem I am facing is to detect whether I have clicked within a rectangle or not. I know there is a function like Rectangle.Contains(Point). To use such method I need to use a for loop to check against each rectangle. If I have a large number of rectangles present, then its not wise to use this method. Is there any other way to do this task.


Solution

  • You need to use a spatial index to find quickly in which rectangle the mouse is. I suggest a R-tree, here is the theorical part:

    http://en.wikipedia.org/wiki/R-tree

    And the c#,implementation:

    http://sourceforge.net/projects/cspatialindexrt/

    Create an rtee, add your rectangles then call the rtree.nearest method with the mouse coordinate to know the rectangles containing the mouse cursor. You can play with the distance parameter.

    Hope it helps,

    Anben Panglose.