I need to get the value of Image rectangle from Non public members of picturebox.
How to get that value?
Thanks in advance.
I need to get the value of Image rectangle from Non public members of picturebox.
How to get that value?
Thanks in advance.
This is how to get the value, using reflection:
PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle",
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
Rectangle rectangle = (Rectangle)pInfo.GetValue(pictureBox1, null);
Although, as Jon has said, there may be a better way of achieving what you're trying to do. Accessing private members through reflection is usually a pretty big code smell.
Well, you could do it with reflection... but you shouldn't. It's not clear exactly what you mean by "value of Image rectangle" but you should definitely try to do all this through the public API. What are you trying to achieve? There may be a different way.
EDIT: Okay, now I see the property you're trying to access... you may be interested in this Connect issue filed in 2004. You're not the only one to want this... although whether you need it for the same reason or not, I don't know.
Although Nivas didn't state what he wanted to accomplish, I suspect it is similar to what I just looked at - translating a user-drawn (ie, crop) rectangle into the picturebox's image space. I didn't try inheritance as RvdK suggested, I used the reflection method as a quick workaround. An alternative to RvdK's suggestion or Microsoft opening up get access to ImageRectangle, would be to provide a RectangleToImageRectangle method. Which I suppose I could wrap in an object that inherits from PB...
The Microsoft Connect Issue link is broken.
Here is the code I used, it provides the rectangle of the PB's image, and was tested for .Zoom and .StretchImage modes:
PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle",
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
Rectangle ImRectangle = (Rectangle)pInfo.GetValue(pictureBox1, null);
Point rTL = new Point((rectCropArea.Left - ImRectangle.Left) * pictureBox1.Image.Width / ImRectangle.Width,
(rectCropArea.Top - ImRectangle.Top) * pictureBox1.Image.Height / ImRectangle.Height);
Size rSz = new Size(pictureBox1.Image.Width * rectCropArea.Width / ImRectangle.Width,
pictureBox1.Image.Height * rectCropArea.Height / ImRectangle.Height);
'rect' = new Rectangle(rTL,rSz);