sách gpt4 ai đã đi

Gọi hàm C# (tệp .cs) từ tệp javascript (tệp .js)

In lại 作者:行者123 更新时间:2023-11-28 02:20:02 25 4
mua khóa gpt4 Nike

我有一个 javascript 文件,并且在该方法中有一个“测试”方法,我喜欢调用 C# 函数。

c# 函数与 javascript 文件不在同一文件中。

它位于 .cs 文件中。那么我该如何管理 javascript 函数能够调用 c# 函数呢?

我已经在互联网上搜索过,但大多数解决方案都是基于 aspx 和 apx.cs 文件...

我尝试过这样的事情:

查看器.js

function Test() {
alert("Hello world-2");
window.external.MethodToCallFromScript();
}

ScriptManager.cs

[ComVisible(true)]
public class ScriptManager
{
public void MethodToCallFromScript()
{
Debug.WriteLine("test");
}
}

但是没有成功...

有人可以帮助我吗?

Cảm ơn!

1 Câu trả lời

为了使其正常工作,您必须设置 WebBrwoser 控件的 ObjectForScripting tài sản.

这是一个例子

using System;
using System.Windows.Forms;
using System.Security.Permissions;

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();

[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}

public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}

private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;

webBrowser1.DocumentText =
"
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code" +
"";
}

public void Test(String message)
{
MessageBox.Show(message, "client code");
}

private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}

}

đây是链接。

关于c# - 从 javascript 文件(.js 文件)调用 C# 函数(.cs 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15785330/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com