问题
I am currently developing an IE toolbar button in C# that is supposed to be able to get the contents of the current tab and work with it. However, whenever the button is clicked, the IObjectWithSite.SetSite function is called ( my code will be posted at the end) and returns the following error:
Unable to cast COM object of type 'System.__ComObject' to interface type SHDocVw.IWebBrowser2'. This operation failed because the QueryInterface call on the COM componenet for the interface with IID '
The function works properly when a site is loaded, but only throws this error when the button in the tool bar is clicked. As stated before, the SetSite function get called, and then the IOleCommandTarget.Exec function gets called.
So, I guess my question is: what do I cast the object that is passed into the SetSite function so that I can access the document on the tab that Internet Explorer currently has open?
My current relevant code for those two functions is as follows:
int IObjectWithSite.SetSite(object site)
{
String display = "";
try { browser = (IWebBrowser2)site;}
catch (Exception e) { display += e.Message + "\r\n"; }
System.Windows.Forms.MessageBox.Show(display);
return 0;
}
int IOleCommandTarget.Exec(IntPtr pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (form == null)
{
form = new SomeForm();
form.InputText = "";
}
form.ShowDialog();
return 0;
}
Thanks in advance.
回答1:
The documented way to query IWebBrowser2 from the toolbar button site is to query IServiceProvider from the site then QueryService for IID_IWebBrowserApp
回答2:
The Exec function calls SetSite before actually executing. In order to work around this and still have the Exec function be able to access information about the browser, the SetSite and GetSite functions should exist in a separate class that the Exec function accesses.
来源:https://stackoverflow.com/questions/6075508/internet-explorer-addon-toolbar-button-error