PictureBox RectangleToScreen coordinates problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

Beginning to tear my hair out (and there's not much there to start)

The problem can be produced by creating a simple C# windows app.
Place a PictureBox on the form.
Make the PictureBox location 32,32 so it sits in the top left of the
form
Make the PictureBox borderstyle = fixedsingle so you can see it.
Create a MouseEnter event handler for the PictureBox
Create a MouseLeave event handler for the PictureBox

And then use the following code to handle the event,

private void pictureBox1_MouseEnter(object sender, System.EventArgs e)
{

// unbox the PictureBox
PictureBox WorkingPicture = (PictureBox)sender;
// create screen coords Rectangle Object of the PictureBox
Rectangle Rect =
RectangleToScreen(WorkingPicture.ClientRectangle);

// create screen coords Rectangle Object of the main form
Rectangle Rect1 = RectangleToScreen(this.ClientRectangle);
}

If you now set a breakpoint and look at the contents of the rect and
rect1 you get

rect PictureBox {X=114 Y=133 Width=98 Height=48}
rect1 Parent form {X=114 Y=133 Width=292 Height=273}

The correct width and height are reported in both cases but the top
left location X and Y are same, but they shouldn't be. Hence the Top
Bottom Left and Right properties for both Rectangles are the same
also.

The wrong values are being reported for the PictureBox. I need the
rect to report the screen coordinates of the PictureBox not the Parent
form.

What am I missing!. Help!!

Many thanks

Cheers

Bob C.
(Surrey UK)
 
I am using RectangleToScreen, just not in the right way.

Another couple of hours gone. Answering my own question

To get the correct ClientRectangle for the parent form use...

Rectangle Rect = RectangleToScreen(this.ClientRectangle);

This will fill Rect with what you would expect

If you use.....

Rectangle Rect = RectangleToScreen(this.pictureBox1.ClientRectangle);

This will provide the right size of the picturebox but the coords are
screwed. It reports those of the parent form as in the first rect
above

To get the PictureBox data correct you have to use

Rectangle Rect = this.pictureBox1.RectangleToScreen(ClientRectangle);

Looking at this specific case I can see the logic. But I obviously
don't understand how these classes all relate to one another. Can
anyone point me in the right direction so that I can.

Thanks again

Bob C
(Surrey, UK)
 
Back
Top