In the original winform, we only need to set a [system. runtime. interopservices. comvisibleattribute (true)] in the header of the Form class.
Then webbrowser1.objectforscripting = this;
In this way, the JS on the page will be able to access the methods in our program after the settings are complete, but if this is set in WPF, a series of error messages will be prompted:
The QueryInterface call is executed to provide the default idispatch interface of the "cloud. mainwindow" hosted class visible to com. However, because this class does not have an explicit default Interface and is derived from the non-com-visible class "system. Windows. Window", the QueryInterface call will fail. The purpose is to prevent non-com visible base classes from being restricted by com version rules.
Why is this error not clear to me...
Then, Google found a solution for a foreign website to create a class.
[System. runtime. interopservices. comvisibleattribute (true)] // set this class to com accessible
Public class objectforscriptinghelper
{
Mainwindow;
Public objectforscriptinghelper (mainwindow main)
{
Mainwindow = Main;
}
// This method is the method for asking questions on the webpage.
Public void htmlcmd (string cmd)
{
MessageBox. Show (CMD );
}
}
Then add the call in our WPF form
Objectforscriptinghelper helper = new objectforscriptinghelper (this );
This. webbrowser. objectforscripting = helper;
OK!