JavaScript调用C#方法

最近在做winform的项目,遇到了很多麻烦的事情,涉及到透明控件,圆角控件等界面渲染总是比较麻烦,重绘,自定义控件,而且发现好像这一块用的人已经不多了,想起之前的有过的想法用html来实现界面渲染,是以,再继续研究研究这一方面的知识。

首先要设置类的COM属性,使其为真。还要设置ObjectForScripting这个属性。案例如下:

 //为了使网页能够与winform交互 将com的可访问性设置为真
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //this.webBrowser.ScriptErrorsSuppressed = true; //禁用错误脚本提示
            this.webBrowser.IsWebBrowserContextMenuEnabled = false; // 禁用右键菜单
            this.webBrowser.WebBrowserShortcutsEnabled = false; //禁用快捷键
            //this.webBrowser.AllowWebBrowserDrop = false; // 禁止文件拖动
            this.webBrowser.Navigate("E:/Project/HTMLWIN/HtmlDemo/Content/Html/HTMLPage7.html");
        }
        
        public void SaveProgress(string str)
        {
            MessageBox.Show("html在调用C#中的方法。SaveProgressstr="+ str);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //获取或设置一个对象,该对象可由显示在 System.Windows.Forms.WebBrowser 控件中的网页所包含的脚本代码访问。
            this.webBrowser.ObjectForScripting = this;
        }

在JavaScript中调用C#的函数的格式如下: window.external.function(params);function是在C#中声明的函数。如下所示:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="../../Scripts/jquery-1.11.1.js"></script>
    <script src="../../Scripts/jquery-1.11.1.min.js"></script>
    <script>
        //把数据传给C#
        function commitDataToC(str) {
            window.external.SaveProgress(str);
        }
    </script>
</head>
<body>
    <input type="button" value="直接调用C#函数" onclick="commitDataToC('js传数据给C#')"/>
</body>
</html>

 记录之。

猜你喜欢

转载自blog.csdn.net/ezreal_pan/article/details/87865181