简体   繁体   English

读取 mshtml.HTMLDocument.Script 属性时出现 InvalidCastException

[英]InvalidCastException when reading mshtml.HTMLDocument.Script property

Trying to read the mshtml.HTMLDocument property results in the following exception:尝试读取 mshtml.HTMLDocument 属性会导致以下异常:

An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll Additional information: Specified cast is not valid. mscorlib.dll 中发生了“System.InvalidCastException”类型的未处理异常附加信息:指定的转换无效。 occurred发生了

This is happening on the line "object script = doc.Script;"这发生在“object script = doc.Script;”这一行上。

Code:代码:

using System;
using System.Reflection;
using mshtml;
using SHDocVw;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            string command = string.Empty;

            while (command != "exit")
            {
                Console.Write("Enter command: ");
                command = Console.ReadLine();

                if (command == "go")
                {
                    ShellWindows shellWindows = new SHDocVw.ShellWindows();
                    foreach (var shellWindow in shellWindows)
                    {
                        var ie = shellWindow as SHDocVw.InternetExplorer;
                        if (ie != null)
                        {
                            var doc = ie.Document as HTMLDocument;
                            if (doc != null)
                            {
                                if (doc.title.Contains("Test Page"))
                                {
                                    object script = doc.Script;
                                    script.GetType().InvokeMember("DoSomething", BindingFlags.InvokeMethod, null, script, null);
                                }
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Unrecognized command");
                }
            }
        }
    }
}

Here is the test page I am using:这是我正在使用的测试页面:

<!DOCTYPE html>
<html>
<head>
  <title>Test Page</title>
</head>
<body>

<script>

function sayHello()
{
    alert('Hello');
}

</script>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

and here are my project references:这是我的项目参考:

    <Reference Include="Interop.SHDocVw">
      <HintPath>..\..\..\TestApp\lib\Interop.SHDocVw.dll</HintPath>
      <EmbedInteropTypes>True</EmbedInteropTypes>
    </Reference>
    <Reference Include="Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      <EmbedInteropTypes>False</EmbedInteropTypes>
    </Reference>

Turns out all I needed to do was run it as single-threaded apartment.原来我需要做的就是将它作为单线程单元运行。 This answer gave me the hint I needed: https://stackoverflow.com/a/19275241/2382032这个答案给了我我需要的提示: https://stackoverflow.com/a/19275241/2382032

using System;
using System.Reflection;
using System.Threading;
using mshtml;
using SHDocVw;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            string command = string.Empty;

            while (command != "exit")
            {
                Console.Write("Enter command: ");
                command = Console.ReadLine();

                if (command == "go")
                {
                    Thread thread = new Thread(() =>
                    {
                        ShellWindows shellWindows = new SHDocVw.ShellWindows();
                        foreach (var shellWindow in shellWindows)
                        {
                            var ie = shellWindow as SHDocVw.InternetExplorer;
                            if (ie != null)
                            {
                                var doc = ie.Document as HTMLDocument;
                                if (doc != null)
                                {
                                    if (doc.title.Contains("Test Page"))
                                    {
                                        object script = doc.Script;
                                        script.GetType().InvokeMember("sayHello", BindingFlags.InvokeMethod, null, script, null);
                                    }
                                }
                            }
                        }
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                }
                else
                {
                    Console.WriteLine("Unrecognized command");
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# - 从 HttpSessionState 读取时出现 InvalidCastException - C# - InvalidCastException when reading from HttpSessionState 从会话状态读取时,InvalidCastException异常 - InvalidCastException exception when reading from session state 在具有 DateTime 属性的实体上使用 IncludeFilter 时出现 InvalidCastException” - InvalidCastException when using IncludeFilter on entity with DateTime property" 使用mshtml HTMLDocument修改DOM并在IE浏览器扩展/ BHO中显示 - use mshtml HTMLDocument to modify DOM and display in IE browser extension/ BHO mshtml.HTMLDocument如何使用class属性隐藏动态创建的div - mshtml.HTMLDocument how to hide a dynamically created div with class attribute 无法将类型“mshtml.IHTMLDocument2”转换为“System.Windows.Forms.HtmlDocument” - Cannot convert type 'mshtml.IHTMLDocument2' to 'System.Windows.Forms.HtmlDocument' c# 指定的转换在分配 mshtml.HTMLDocument.frames 时无效 - c# specified cast is not valid while assigning mshtml.HTMLDocument.frames 如何使用.NET的WebBrowser或mshtml.HTMLDocument动态生成HTML代码? - how to dynamically generate HTML code using .NET's WebBrowser or mshtml.HTMLDocument? 序列化和反序列化时出现InvalidCastException - InvalidCastException when serializing and deserializing 在检查空值后从OdbcDataReader读取值时,为什么会收到InvalidCastException? - Why do I get an InvalidCastException when reading values from OdbcDataReader after checking for null values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM