将InvokeMember与WPF WebBrowser HTMLElement一起使用会引发异常

时间:2018-10-04 09:32:12

标签: c# wpf webbrowser-control invokemember

我正在尝试模拟用户在网站的“输入”字段中键入值,并且在尝试运行InvokeMember时遇到非常奇怪的异常。我测试了几种方法,发现大多数在线文档已经过时,根本无法使用。不幸的是,对我的问题提出最多建议的解决方案似乎引发了一个非常奇怪的异常:

  

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:   ''System.MarshalByRefObject.InvokeMember(string,   System.Reflection.BindingFlags,System.Reflection.Binder,object [],   System.Reflection.ParameterModifier [],   由于以下原因,无法访问System.Globalization.CultureInfo,string [])'   它的保护级别”

这是重新产生问题的示例代码:

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
        }
    }
}

input.InvokeMember("click");行抛出该异常,但是input.click();正常工作。

该异常的原因是什么?

0 个答案:

没有答案