Jun 26, 2012

How to get visible/Viewable area of User control(C#)?

4 comments
I have a control whose parent is a scroll-able control. How to find the part of the control that's actually visible to the user? See the following screen shots.


Fig.1 Before Resize - Picture box surrounded by red rectangle is the complete control

After re-sizing of parent form till the part of picture box is invisible(See below screen shot, we have to find out the visible area(user can see) of picture box.
Fig.2 - After resize - Part of picture box went inside of scrollable control

So How do i find the visible part of the control(here it is Picture box) ?
After spending a whole day finally able to get the solution to for this as follows,


        private void btnGetVisibleArea_Click(object sender, EventArgs e)
        {
            Rectangle rect = GetVisibleRectangle(pictureBox1);

            MessageBox.Show(rect.ToString(), "Visible Area");
        }

        private Rectangle GetVisibleRectangle(Control c)
        {   
            Rectangle rect = c.RectangleToScreen(c.ClientRectangle);
            while (c != null)
            {
                rect = Rectangle.Intersect(rect, c.RectangleToScreen(c.ClientRectangle));
                c = c.Parent;
            }
            rect = pictureBox1.RectangleToClient(rect);
            return rect;
        }

That's it, we are done!

If you feel this is helpful or you like it, Please share this using share buttons available on page.

4 comments :

  1. Thank you so much for this. I am making a 2D Game Engine with Tiles and this is what I used to only Render the tiles that are currently visible (around 1560 at a time instead of 250,000 like I would have been doing normally)

    Again, Thank you!

    ReplyDelete
  2. You should get this article http://spying.ninja/flexispy-spy-review/ to explore a lot of various articleson different topics.

    ReplyDelete
  3. Now i got clear idea about Viewable area of User control(C#).It was great.Thank you so much for sharing... Dot Net Training in Chennai
    Hadoop Training in Chennai

    ReplyDelete