-
C#和JS交互 WebBrowser实例
-
本文实现了WebBrowser的简单例子
-
-
1.引用System.Windows.Froms.dll
-
2.引用WindowsFormsIntegration.dll
-
代码如下:
-
public partial class MainWindow : Window
-
{
-
public MainWindow()
-
{
-
InitializeComponent();
-
}
-
-
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
-
{
-
Window _w = new Window();
-
web_control web_c = new web_control("http://www.baidu.com");
-
_w.Content = web_c;
-
_w.Owner = this;
-
_w.Show();
-
}
-
}
-
-
public class web_control : UserControl
-
{
-
public System.Windows.Forms.WebBrowser _web_browser;
-
public web_control(string url)
-
{
-
_web_browser = new System.Windows.Forms.WebBrowser();
-
_web_browser.ObjectForScripting = new external_dispath(this);
-
var host = new System.Windows.Forms.Integration.WindowsFormsHost();
-
host.Child = _web_browser;
-
Content = host;
-
Loaded += (senser, e) =>
-
{
-
_web_browser.Navigate(url);
-
};
-
}
-
}
-
-
-
至此,上方实现了简单的例子(除了红色那一句之外)
-
-
=========================================17.7.21更新以下========================================================
-
-
但在后来遇到要与JS交互,在webBrowser使用过程中为了C#和JS通讯,webBrowser必须设置ObjectForScripting的属性,
-
它是一个object,这个object可以提供给webBrowser控件载入的网页上的script访问。(上方红色语句)
-
-
在设置过webBrowser控件的ObjectForScripting属性后,还需要设置应用程序对com可见,不然会抛出一个异常
-
(ObjectForScripting 的类必须对 COM 可见。请确认该对象是公共的,或考虑向您的类添加 ComVisible 属性。),可做如下设置:
-
-
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
-
public class external_dispath
-
{
-
public web_control m_wbcontrol;
-
-
public external_dispath(web_control wb_c)
-
{
-
m_wbcontrol = wb_c;
-
}
-
-
public Object createObject(String name)
-
{
-
return new external_dispath(m_wbcontrol);
-
}
-
-
public void closeWebDlg()
-
{
-
(m_wbcontrol.Parent as Window).Close();
-
}
-
通过在c#这一层实现external类,来达到在点击网页中右上角的关闭按钮时,关闭网页的弹窗
-
}
-
-
JS代码:
-
-
$(".close-btn").on("click",function(
-
-
e){
-
e.preventDefault();
-
TA.log({ld:'client', id:'lhb_kx_gb'});
-
try{
-
external.closeWebDlg();
-
-
}catch (e){} });
-
-
最后疑问是external是哪里来的,JS和C#是怎么约定的,以后在学习JS后可能会有深好理解
-
相关阅读:
矩阵树定理 / 生成树计数
NC20811 蓝魔法师 (树形DP/树上01背包)
Xor-MST学习/ 2020牛客暑假多校(五)B.Graph
HDU-6820 Tree (2020杭电多校(五) 1007)
Flipping Coins (概率DP)
宝石装箱 容斥+dp
Rabbit的工作(1) (dP)
Codeforces-1350 E.Orac and Game of Life
HDU-6563 Strength (贪心)
HDU-6558 The Moon (期望DP)
-
原文地址:https://www.cnblogs.com/kevinWu7/p/10163541.html
Copyright © 2020-2023
润新知