RoadBump
RoadBump

Reputation: 751

Child control re-positioned on a auto scroll form when the control is shown

I have a form with AutoScroll set to true. Some controls on the form are invisible when the form starts, but their location is already set. Once the control turns visible, the position is calculated relative to current AutoScrollPosition, which is totally unwanted.

Any idea how to prevent this?

I tried set the position when the control is first shown, as follows:

 void OnControlVisibleChanged(object sender, EventArgs e)
    {
        Control ctl = (Control)sender;
        if (ctl.Visible)
        {
            ctl.Location = Point.Add(ctl.Location, new Size(this.AutoScrollPosition));
            ctl.VisibleChanged -= OnControlVisibleChanged;
        }
    }

It works for some controls, and for others not. I don't know why.
EDIT: it seems that when a control turns visible, the real AutoScrollPosition changes, but the AutoScrollPosition property is not updated immediately.

Upvotes: 1

Views: 228

Answers (1)

LarsTech
LarsTech

Reputation: 81610

The AutoSize = True seems to interfere with your code. I don't know if that's the only point of failure, but this worked in my testing:

void OnControlVisibleChanged(object sender, EventArgs e) {
  Control ctl = (Control)sender;
  if (ctl.Visible) {
    bool moveOK = true;
    if (ctl.GetType().GetProperty("AutoSize") != null) {
      if ((bool)ctl.GetType().GetProperty("AutoSize").GetValue(ctl, null)) {
        moveOK = false;
      }
    }
    if (moveOK) {
      ctl.Location = Point.Add(ctl.Location, new Size(this.AutoScrollPosition));
    }
  }
}

Upvotes: 1

Related Questions