I'm trying to simulate a user typing a value into an "input" field on a website, and I'm getting very strange exception when trying to run InvokeMember. I tested several approaches and I found that most online documentation is outdated and simply doesn't work. Unfortunately the mostly suggested solution to my problem seems to throw a very strange exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.MarshalByRefObject.InvokeMember(string, System.Reflection.BindingFlags, System.Reflection.Binder, object[], System.Reflection.ParameterModifier[], System.Globalization.CultureInfo, string[])' is inaccessible due to its protection level'
This is an example code that recreates the problem:
MainWindow.xaml
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Example"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<DockPanel>
<WebBrowser x:Name="ie"/>
</DockPanel>
</Window>
MainWindow.xaml.cs
using mshtml;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Navigation;
namespace Example
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ie.LoadCompleted += (o, e) =>
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (wo, we) => { Thread.Sleep(5000); };
worker.RunWorkerCompleted += (wo, we) => { DelayedLoadCompleted(); };
worker.RunWorkerAsync();
};
ie.Navigate(@"https://google.com");
}
private void DelayedLoadCompleted()
{
HTMLDocument doc = (ie.Document as HTMLDocument);
dynamic input = doc.getElementById("lst-ib");
input.InvokeMember("onkeypress", new { Key = 65 }); //throws that excetpion
input.InvokeMember("click"); //throws that excetpion
input.click(); //works fine
}
}
}
The line input.InvokeMember("click");
throws that exception, but input.click();
works just fine.
What is the cause of that exception?