简体   繁体   中英

C# Windows Forms - Updating toolStripLabel text returns auto-scrollable panel to top

I have the following form set up:

http://i.imgur.com/BKBGbGw.png (I can't post images due to this account being new)

Whenever I update the text of the underlined ToolStripLabel the scrollbar returns to top, as shown below:

http://i.imgur.com/OVPzDdS.png

This is the code which edits the ToolStripLabel.Text:

private void OnTimedEvent(object source, EventArgs e)//requests data
{
    try
    {
        if (commTool != null)
        {
            pollTimer.Stop();
            commTool.Poll();
            writeRequests(commTool.PollCount.ToString());
            if (!stopTimer)
            {
                pollTimer.Start();
            }
            if (errorRate < 0.25)
            {
                setColour(Color.Green);
            }
            else if (errorRate > 0.25 && errorRate < 0.5)
            {
                setColour(Color.GreenYellow);
            }
            else if (errorRate > 0.5 && errorRate < 0.75)
            {
                setColour(Color.Yellow);
            }
            else
            {
                setColour(Color.Red);
            }
        }
        else
        {
            Console.WriteLine("Error MainMenu.cs, OnTimedEvent(): commTool = null");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error MainMenu.cs, OnTimedEvent(): " + ex.ToString());
    }
}

public void writeRequests(string pollCount)
{
    requests = commTool.PollCount;
    if (statusBar.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(writeRequests);
        Invoke(d, new object[] { pollCount });
    }
    else
    {
        tsLblRequests.Text = "Requests: " + pollCount;
    }
}

Any advice or solutions are much appreciated.

I added checkbox and now I can reproduce this behaviour as well. First I thought that it happens because checkbox got focused when check state changed and, of course, panel will automatically scroll to show the focused control. But then I discovered that it will only scroll if I changed ToolStripLabel text as well, without checking InvokeRequired property.

I see that you already invoking when changing text of tsLblRequests, but might be there is some other labels, which are requiring invoke. I think that might be the case.

If it's not the case, then you can try to adjust scroll position to show specific control with panel1.ScrollControlIntoView(label1) .

If ScrollControlIntoView method is not flexible enough, then might be VScrollBar control will work better for you.

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