简体   繁体   中英

How do I find the visible part of a control?

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.

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;
}

AutoScrollPosition represents the location of the scrollable control's display rectangle. The X and Y coordinate values retrieved are negative if the control has scrolled away from its starting position (0,0). When you set this property, you must always assign positive X and Y values to set the scroll position relative to the starting position. For example, if you have a horizontal scroll bar and you set x and y to 200, you move the scroll 200 pixels to the right; if you then set x and y to 100, the scroll appears to jump the left by 100 pixels, because you are setting it 100 pixels away from the starting position. In the first case, AutoScrollPosition returns {-200, 0}; in the second case, it returns {-100,0}.

Source: MSDN: ScrollableControl.AutoScrollPosition Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM