Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the visible part of a control?

Tags:

c#

.net

winforms

I have a control whose parent is a ScrollableControl. How do I find the part of the control that's actually visible to the user? Both are rectangular - there's no funny business with Regions.

like image 889
Simon Avatar asked May 07 '09 08:05

Simon


1 Answers

I think the GetVisibleRectangle method I wrote below is what you were requesting. Successive runs of this with scrolling yielded the following output as the control was scrolled:

  • {X=0,Y=0,Width=0,Height=0} - button4 was scrolled out of view. Note that the value here is Rectangle.Empty.
  • {X=211,Y=36,Width=25,Height=13} - button4 was scrolled so the upper left corner was visible
  • {X=161,Y=36,Width=75,Height=13} - button4 was scrolled so the top half and entire width was visible
  • {X=161,Y=26,Width=75,Height=23} - button4 was scrolled to be entirely visible

Note how in addition to the Width and Height changes that the X,Y also changed with scrolling.

Source:

private void button1_Click(object sender, EventArgs e)
{
    Rectangle r = GetVisibleRectangle(this.panel1, button4);
    System.Diagnostics.Trace.WriteLine(r.ToString());
}

public static Rectangle GetVisibleRectangle(ScrollableControl sc, Control child)
{
    Rectangle work = child.Bounds;
    work.Intersect(sc.ClientRectangle);
    return work;
}
like image 82
devgeezer Avatar answered Nov 05 '22 07:11

devgeezer