1 回答
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
假設(shè)這是 WinForms,因?yàn)橛幸粋€(gè) WebBrowser 控件,從 HTML 頁(yè)面 JavaScript 調(diào)用 C# 代碼可以用這個(gè)最小的例子來(lái)完成:
將簡(jiǎn)單的 HTML 頁(yè)面添加到項(xiàng)目的根目錄并Properties設(shè)置為此Copy to Output Directory: Copy if newer將確保有一個(gè)簡(jiǎn)單的頁(yè)面用于測(cè)試:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
JS函數(shù)getLocations會(huì)調(diào)用C#方法SendLocations,重要的部分是Form1類注解和設(shè)置webBrowser1.ObjectForScripting = this:
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[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)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
單擊 HTML 按鈕Call C#將顯示一個(gè)彈出窗口,其中包含 C# 方法的返回值

添加回答
舉報(bào)
