尝试读取 mshtml.HTMLDocument 属性会导致以下异常:
mscorlib.dll 中出现“System.InvalidCastException”类型的未处理异常附加信息:指定的强制转换无效。发生了
这发生在“object script = doc.Script;”这一行上。
代码:
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");
}
}
}
}
}
这是我正在使用的测试页面:
<!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>
这是我的项目参考:
<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>