2

I have a a WebBrowser control in my winform application which is used to display pdf files and load webpages on the request of the user. If the file type is not supported or the webpage initiates a download the WebBrowser control wil ask to save, open or cancel the file. I found a sollution here: https://social.msdn.microsoft.com/Forums/windows/en-US/325b1dde-806c-44d9-b420-2e4c929ae09d/webbrowser-control-how-to-disable-file-downloads?forum=winforms

This solution seemed to work but when closing the application I get the following exception: InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.

Is there a better way to block downloads for the WebBrowser control or am I implementing this solution wrong?

I added a reference to 'Microsoft Internet Controls (Interop.SHDocVw.dll)' and added this code to my WebBrowser Control:

(webBrowser.ActiveXInstance as SHDocVw.ShellBrowserWindow).FileDownload += browser_FileDownload;

private void browser_FileDownload(bool ActiveDocument, ref bool Cancel)
{
    if (!ActiveDocument)
        Cancel = true;
}
Maiko Kingma
  • 929
  • 3
  • 14
  • 29
  • There is a good answer [here](http://stackoverflow.com/questions/2260990/com-object-that-has-been-separated-from-its-underlying-rcw-cannot-be-used). – Brian Oct 21 '15 at 18:50

1 Answers1

2

If that is the only change you made that caused this error, then you might try calling this before shutting down:

(webBrowser.ActiveXInstance as SHDocVw.ShellBrowserWindow).FileDownload -= browser_FileDownload;

NOTE: -= (not +=)

jm.
  • 23,422
  • 22
  • 79
  • 93
  • Thanks, that worked. I had to change it to `if (webBrowser.ActiveXInstance != null) (webBrowser.ActiveXInstance as SHDocVw.ShellBrowserWindow).FileDownload -= browser_FileDownload;` in case the webBrowser wasn't used. – Maiko Kingma Oct 23 '15 at 06:45