Cosmin Ioniță
Cosmin Ioniță

Reputation: 4055

How to set the horizontal scroll position to a specified value?

I have a form that contains a very large panel. When I set the panel, I got the scrollbars on the margins of the form.

Now, I want to set the horizontal scrollbar to a specified position, so that when I start my application, the scrollbar should be positioned at the middle of the panel (I want to see the middle of the panel when I start my app).

How can I do that?

I found that possible solution: http://www.codeproject.com/Articles/10839/How-to-change-scrollbars-position-in-a-multiline-t, but the problem is that it refers to a multiline textbox. I want to do that for a form.

Upvotes: 2

Views: 10424

Answers (1)

LarsTech
LarsTech

Reputation: 81620

You can set the middle by offsetting the scroll size from the client width:

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);

  panel1.AutoScroll = false;
  panel1.AutoScrollMinSize = new Size(1000, 0);
  panel1.AutoScrollPosition = new Point((panel1.AutoScrollMinSize.Width -
                                         panel1.ClientSize.Width) / 2, 0);
}

Since you have a panel larger than the form, you can try it this way (I'm assuming the panel is located at the X=0 position:

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  this.AutoScroll = false;
  this.AutoScrollMinSize = new Size(panel1.Width, 0);
  this.AutoScrollPosition = new Point((this.AutoScrollMinSize.Width -
                                       this.ClientSize.Width) / 2, 0);
}

Upvotes: 2

Related Questions