我正在尝试模拟用户在网站上的“输入”字段中输入值,并且在尝试运行 InvokeMember 时遇到非常奇怪的异常。我测试了几种方法,发现大多数在线文档已经过时并且根本不起作用。不幸的是,针对我的问题的大多数建议解决方案似乎引发了一个非常奇怪的异常:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.MarshalByRefObject.InvokeMember(string, System.Reflection.BindingFlags, System.Reflection.Binder, object[], System.Reflection.ParameterModifier[], System.Globalization.CultureInfo, string[ ])'由于其保护级别而无法访问'
这是重现问题的示例代码:
主窗口.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>
主窗口.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
}
}
}
该行input.InvokeMember("click");
抛出该异常,但input.click();
工作得很好。
该异常的原因是什么?