Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

windows forms: scroll programmatically

I'm developing a windows forms application. And i have the following issue: in a form there's a panel, and in that panel i have a number of controls (just a label with a text box, the number is determined at runtime). This panel has a size that is smaller than the sum of all the controls added dynamically. So, i need a scroll. Well, the idea is: when the user open the form: the first of the controls must be focused, the the user enters a text and press enter, the the next control must be focused, and so until finished.

Well it's very probably that not all the controls fit in the panel, so i want that when a control inside the panel got focus the panel scrolls to let the user see the control and allow him to see what he is entering in the text box.

I hope to be clear.

here is some code, this code is used to generated the controls and added to the panel:

    List<String> titles = this.BancaService.ValuesTitle();
    int position = 0;
    foreach (String title in titles)
    {
         BancaInputControl control = new BancaInputControl(title);
         control.OnInputGotFocus = (c) => {
                 //pnBancaInputContainer.VerticalScroll.Value = 40;
                 //pnBancaInputContainer.AutoScrollOffset = new Point(0, c.Top);
                 // HERE, WHAT CAN I DO?
                 };
         control.Top = position;
         this.pnBancaInputContainer.Controls.Add(control);
         position += 10 + control.Height;
    }
like image 546
Müsli Avatar asked Apr 23 '26 15:04

Müsli


1 Answers

If you set AutoScroll to true this will be taken care of automatically. As for the idea that Enter should move focus to next field, the best solution would be to execute enter as if it was TAB key in BancaInputControl:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);

    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        //  Move focus to next control in parent container
        Parent.SelectNextControl(this, true, true, false, false);
    }
}

If BancaInputControl is composite control (a UserControl containing other controls) each child control should hook up KeyDown event to this handler. It tries to move focus to next control in BancaInputControl; if it fails, moves focus to parent container's next control.

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        if (!SelectNextControl((Control)sender, true, true, false, false))
        {
            Parent.SelectNextControl(this, true, true, false, false);
        }
    }
}
like image 50
Nikola Markovinović Avatar answered Apr 26 '26 07:04

Nikola Markovinović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!