0
votes

In my WPF application I have a WebBrowser control. I have a grid containing files, and when I click on an item in the grid the file contents are retrieved from a database to be shown in the WebBrowser.

There are two types of file:

PDF: a temporary file is created, and the web broswer Navigate function is used to load the file.

HTML: The string is passed to the NavigateToString function.

If I view a PDF, then a HTML document, right clicking shows the context menu. I want to keep most things, such as print, but I want to stop the browser from letting the user go back a page, or even forwards.

Without editing the content to add Javascript etc, is there anything on the control I can do to stop the back/forward from happening?

2

2 Answers

0
votes

The answer I have come up with is the Navigated event. The user control that contains the web browser has a private boolean that determines if navigation is allowed.

If it is (set through the user control's Navigate method) then the control can navigate to a new page. Once the page has loaded the boolean is set to false, meaning back / forward is disabled.

In my case this adds a bonus: Links cannot be clicked on. I don't want these loading in the browser control - I only want this to view pages selected in the grid.

However, right-click on a link still has the open in a new window option.

This may not be the best solution, but it works for me.

0
votes

To disable the backspace for navigating back but still keep the link clickable and backspace function for textbox, we need to add event handler for both PreviewKeyDown and Navigating event for WebBrowser:

// member variable to indicate if the window allows navigation to other URL
private bool allowNavigation = false;
private WebBrowser bs;

// triggered every time a key is pressed down in the WebBrowser
this.bs.PreviewKeyDown += (sender, args) =>
{
    if (args.Key == Key.Back)
    {
        // temporarily disable navigation triggered by backspace
        this.allowNavigation = false;
    }
};
// triggered if the WebBrowser is switching URL (either by backspace or link clicking)
this.bs.Navigating += (sender, args) =>
{
    if (!allowNavigate)
    {
        // if not allowed, cancel navigation and set back allowNavigation
        // this will only cancel the navigation triggered by backspace
        args.Cancel = true;
        this.allowNavigation = true;
    }
};