首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WinForm:与WinForm通信时出错

WinForm:与WinForm通信时出错
EN

Stack Overflow用户
提问于 2015-06-02 00:24:35
回答 1查看 64关注 0票数 0

我正在开发一个应用程序来实现网站和C# WebForm之间的双向通信。webform能够通过按钮与网页的脚本通信,但脚本不能与网页表单通信。单击时,该按钮会显示以下错误:

'window.external' is null or not an object.

C#代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2015-06-02 02:35:58

下面这两行解决了我的问题。没有伴随的或相关的错误,这是随机的运气,我看到依赖项没有声明。

代码语言:javascript
复制
// new
using System.Security;
...
// already in code
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30578494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档