I have a .Net Panel control that contains a single child control that is a WebBrowser. I won't go into the reasons for me doing that, but it is related to printing out the control. The panel control has its AutoScroll property set to "true" and I am sizing the WebBrowser to fit its own content (by using the .Document.Body.ScrollRectangle.Size property of the WebBrowser when the NavigateComplete2 event fires). In this way, the scrollbar on the panel appears and you can scroll the panel up and down in order to be able to see the content of the WebBrowser.
The problem is that when you scroll down to see what's at the bottom of the WebBrowser and then click on it (perhaps you click on a link in the html), the panel jumps back to the top and the link doesn't get actioned.
Please can anyone help me to understand what's going on and how to get around this problem?
I had the same problem, also with a WebBrowser inside a Panel. Here's the solution I'm using (which I found somewhere else on stackoverflow):
class AutoScrollPanel : Panel
{
public AutoScrollPanel()
{
Enter += PanelNoScrollOnFocus_Enter;
Leave += PanelNoScrollOnFocus_Leave;
}
private System.Drawing.Point scrollLocation;
void PanelNoScrollOnFocus_Enter(object sender, System.EventArgs e)
{
// Set the scroll location back when the control regains focus.
HorizontalScroll.Value = scrollLocation.X;
VerticalScroll.Value = scrollLocation.Y;
}
void PanelNoScrollOnFocus_Leave(object sender, System.EventArgs e)
{
// Remember the scroll location when the control loses focus.
scrollLocation.X = HorizontalScroll.Value;
scrollLocation.Y = VerticalScroll.Value;
}
protected override System.Drawing.Point ScrollToControl(Control activeControl)
{
// When the user clicks on the webbrowser, .NET tries to scroll to
// the control. Since it's the only control in the panel it will
// scroll up. This little hack prevents that.
return DisplayRectangle.Location;
}
}
try setting TabStop to false on both the containing panel as well as the WebBrowser control. That did the trick for me. The reason this works is that if it's set as a wanting to be a tabstop, it will take the first click event to mean that it's receiving focus. This then resets the scroll bar positions... not sure why it does that...
However, on navigating to a new page you'll need to manually reset the scroll bar positions...
Here is what I used. Yeah it's a hack.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
webBrowser1.TabStop = true;
webBrowser1.Focus();
webBrowser1.TabStop = false;
}