0

I am implementing a custom drag and drop interface with winForm Buttons and after viewing several solutions on how to obtain mouse position and check it against control bound have not been able to get it to work.

I have tried:

button.ClientRectangle.Contains(PointToClient(Cursor.Position))

and

button.ClientRectangle.Contains(PointToClient(Control.MousePosition))

Both of these have failed to work. Checking the mouse bounds seem like a simple operation, but I really am stumped.

My speculation of the unexpected values are:

  1. Process of obtaining cursor position may be in wrong corner of cursor image
  2. Method/Function does not work on Buttons for some reason
Bennett Yeo
  • 819
  • 2
  • 14
  • 28

1 Answers1

2

You are using the wrong object reference, calculating the mouse position relative to the form instead of the button. And you are writing it in a way that make this very hard to debug. Fix:

var pos = button.PointToClient(Cursor.Position);
System.Diagnostics.Debug.WriteLine(pos);         // Now it is easy
if (button.ClientRectangle.Contains(pos)) {
    // etc...        
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Ah that makes sense, I hadn't really had much experience with using PointToClient and the whole "relativistic positions", so this makes more sense. – Bennett Yeo Aug 30 '15 at 22:25