Sorry a bit late, but I finally am able to disable the scrollbar. The hint from @Devdude was the key.
The main point is to set the overflow = hidden
, but how to do that in WPF? I used DependencyObject
so that I can bind: enable and disable whenever I want.
First of all you need to add reference to mshtml
. In your project, add reference add Microsoft.mshtml
. Then in your .cs
file add:
using mshtml;
The DependencyObject
public class WebBrowserUtility : DependencyObject
{
public static readonly DependencyProperty HideScrollBarProperty = DependencyProperty.RegisterAttached(
"HideScrollBar",
typeof(string),
typeof(WebBrowserUtility),
new UIPropertyMetadata(null, HideScrollBarPropertyChanged));
public static string GetHideScrollBar(DependencyObject obj)
{
return (string)obj.GetValue(HideScrollBarProperty);
}
public static void SetHideScrollBar(DependencyObject obj, string value)
{
obj.SetValue(HideScrollBarProperty, value);
}
public static void HideScrollBarPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
WebBrowser browser = obj as WebBrowser;
string str = args.NewValue as string;
bool isHidden;
if (str != null && bool.TryParse(str, out isHidden))
{
browser.HideScrollBar(isHidden);
}
}
}
The WebBrowser
Extension, which actually does the work to disable the overflow, which only happens after WebBrowser
Document Load is Completed:
public static class WebBrowserExtension
{
public static void HideScrollBar(this WebBrowser browser, bool isHidden)
{
if (browser != null)
{
IHTMLDocument2 document = browser.Document as IHTMLDocument2;
if (document == null)
{
// If too early
browser.LoadCompleted += (o, e) => HideScrollBar(browser, isHidden);
return;
}
//string bodyOverflow = string.Format("document.body.style.overflow='{0}';", isHidden ? "hidden" : "auto");
//document.parentWindow.execScript(bodyOverflow); // This does not work for me...
string elementOverflow = string.Format("document.documentElement.style.overflow='{0}';", isHidden ? "hidden" : "auto");
document.parentWindow.execScript(elementOverflow);
}
}
}
To use in the XAML
<WebBrowser ns:WebBrowserUtility.HideScrollBar="True"/>
Note: Make sure that you stretch the WebBrowser
to see the whole contents. Regardless, the scrollbar
will be hidden this time.