c# - 将 InvokeMember 与 WPF WebBrowser HTMLElement 一起使用会引发异常
问题描述
我正在尝试模拟用户在网站上的“输入”字段中输入值,并且在尝试运行 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();
工作得很好。
该异常的原因是什么?
解决方案
推荐阅读
- c# - 字符串中每个字母后的换行符
- javascript - 获取上传图片的位置
- java - 如何确保用户不能在同一台计算机上做某事
- sql - 将两列数据与第二列的第一个字符组合成一列,留下空值
- reactjs - React - 如何从子功能组件执行功能
- python - 从其他 Python 文件调用函数时的问题
- three.js - glTF 2.0 视频纹理支持
- actions-on-google - 如何获得 Google 的“书面许可”以使用 Google Assistant SDK 将我的项目商业化?
- amadeus - 如何通过 Amadeus Hotel 服务连接客房
- google-bigquery - 使用命令将数据库(具有嵌套文档)从 Cloud Firestore 导出到 Bigquery