Invalid Exception Exception Error for Windows Service Webbrowser

I am having problems with the Windows Service web browser. It tries to upload the username and password values ​​to the site, but continues to fail and throws the following error:

System.InvalidCastException: Specified cast is not valid. at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation() at System.Windows.Forms.WebBrowser.get_Document() at MyWindowsService.MyDataProcessor.login()

The code I use for this call is:

 MyWebBrowser.Document.All["Login"].SetAttribute("Value", username); MyWebBrowser.Document.All["Password"].SetAttribute("Value", password); MyWebBrowser.Document.All["submit"].InvokeMember("Click"); 

Any ideas as to why he continues to fail? Thank you in advance.

+4
source share
2 answers

I had a similar problem using SHDocVW.WebBrowserClass. I got an InvalidCastException when I tried to access Document.all from the SHDocVW.WebBrowserClass instance (from the main thread) and I was able to fix it by switching to IHTMLDocument2 instead of HTMLDocument. It took me a long time to realize that most of the time it works in HTMLDocument.

 SHDocVW.WebBrowserClass Explorer = [instance of IE]; ((IHTMLDocument2)Explorer.Document).all // works all the time ((HTMLDocument)Explorer.Document).all // works some times 

I hope this helps someone.

+1
source

I'm not sure if this solves the problem, but you can check the InvokeRequired property on the current object or WebBrowser.InvokeRequired and use something like MethodInvoker to call your function or helper function to access WebBrowser.Document.

http://www.megasolutions.net/cSharp/(WebBrowser_Document-==-null)-throws-InvalidCastException-43126.aspx

0
source

Source: https://habr.com/ru/post/1302812/


All Articles