国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#通過html調用WinForm的方法

2019-10-29 21:29:33
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了C#通過html調用WinForm的方法,涉及html頁面中使用JavaScript訪問C#的相關技巧,需要的朋友可以參考下
 

本文實例講述了C#通過html調用WinForm的方法。分享給大家供大家參考,具體如下:

完整測試代碼:

Form1.cs:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace test{  [System.Runtime.InteropServices.ComVisibleAttribute(true)]  public partial class Form1 : Form  {    public Form1()    {      InitializeComponent();    }    private void Form1_Load(object sender, EventArgs e)    {      System.IO.FileInfo file = new System.IO.FileInfo(Application.StartupPath+@"/test1.htm");      webBrowser1.Url = new Uri(file.FullName);      webBrowser1.ObjectForScripting = this;    }    private void button1_Click(object sender, EventArgs e)    {      object[] objects = new object[1];      objects[0]="C#訪問javascript腳本";      webBrowser1.Document.InvokeScript("messageBox", objects);    }    public void MyMessageBox(string message)    {      MessageBox.Show(message);    }  }}

類WinOper:

[System.Runtime.InteropServices.ComVisibleAttribute(true)]  public class WinOperationClass  {    public void MyMessageBox1()    {      MessageBox.Show(message);    }    public void ShowForm()    {      Form2 f2 = new Form2();      f2.WindowState = FormWindowState.Normal;      f2.Show();    }  }

網頁:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html>  <head>    <title></title>    <script language="javascript" type="text/javascript">      function messageBox(message)      {        alert(message);      }    </script>  </head>  <body>    <button onclick="window.external.MyMessageBox('javascript訪問C#代碼')">javascript訪問C#代碼</button>      <a href="javascript:window.external.MyMessageBox1()">javascript訪問C#代碼</a>    <a href="javascript:window.external.ShowForm()">javascript訪問C#代碼</a>  </body></html>

補充:

webBrowser1.ObjectForScripting = this;

這句話的意思是webBrowser1的腳本執行的Com綁定的方法是 從Form1 來的,而MyMessageBox1和ShowForm卻是在WinOperationClass類里面的,肯定是不行的。

第一個可以是因為form1里面有MyMessageBox這個方法,你吧MyMessageBox1和ShowForm移動到form1中或者把MyMessageBox移動到WinOperationClass里面,再把

webBrowser1.ObjectForScripting = this;

這句改成

WinOperationClass w=new WinOperationClass();webBrowser1.ObjectForScripting = w;

就可以了

推薦第二種……把所有的 Com可見的方法放在一個類里面好維護



注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黔西县| 徐闻县| 梁河县| 靖宇县| 伊宁市| 卢氏县| 潜江市| 西平县| 西畴县| 方正县| 灵石县| 汕头市| 健康| 西华县| 即墨市| 深泽县| 偏关县| 敖汉旗| 峨眉山市| 阿克陶县| 蓝田县| 雅安市| 文化| 巫溪县| 汉寿县| 会宁县| 淳安县| 金平| 民丰县| 许昌市| 蛟河市| 资阳市| 历史| 吴忠市| 开江县| 紫云| 茂名市| 杭锦旗| 宁阳县| 平遥县| 旬阳县|