【问题标题】:WinForms: When ObjectForScripting is set, HTML is not displayedWinForms:设置 ObjectForScripting 时,不显示 HTML
【发布时间】:2015-08-15 02:16:36
【问题描述】:

我有一个 Windows 窗体应用程序和一个单独的 HTML 页面。两个人应该互相交流。我按照this microsoft link 的说明进行操作。在我使用WebBrowser.ObjectForScripting = this; 设置ObjectForScripting 之前,HTML 页面显示正确。但是,设置ObjectForScripting 后,HTML 将不会显示在 WebBrowser 组件中。它给出了错误“window.external is null or not an object。”

C#代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FirstCSharpApp
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WebBrowser.AllowWebBrowserDrop = false;
            WebBrowser.IsWebBrowserContextMenuEnabled = false;
            WebBrowser.WebBrowserShortcutsEnabled = false;
            WebBrowser.ObjectForScripting = this;

            string curDir = Directory.GetCurrentDirectory();
            WebBrowser.Navigate(new Uri(String.Format("file:///{0}/Timeline.html", curDir)));
        }

        private void GoButton_Click(object sender, EventArgs e)
        {
            // Works!
            WebBrowser.Document.InvokeScript("test",
                new String[] { "called from client code" });
        }

        private void homeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebBrowser.GoHome();
        }

        private void goBackToolStripMenuItem_Click(object sender, EventArgs e) 
        {
            WebBrowser.GoBack();
        }

        private void goForwardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebBrowser.GoForward();
        }

        public void Test(String message)
        {
            // Does not work, or apparently even exist
            MessageBox.Show(message, "client code");
        }
    }
}

HTML:

<html>
<head>
    <script>
        function test(message) {
            alert(message);
        }
    </script>
</head>

<body>
    <button onclick ="window.external.Test('called from script')">
        Call client code.
    </button>
</body>
</html>

【问题讨论】:

  • 您确实应该包含您的代码,以防万一出现复制粘贴错误。这是最常见的错误之一。

标签: c# html winforms object


【解决方案1】:

您的表单类中似乎缺少这些属性。

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]

您可以将此属性设置为您想要的任何 COM 可见对象 其可用于脚本代码的公共属性和方法。你可以 用ComVisibleAttribute 标记一个类COM 可见。

【讨论】:

  • 根据我对文档的理解,如果是public,它已经被标记为 Com Visible。无论如何我标记了它,它并没有解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2013-08-10
相关资源
最近更新 更多