|
|
<div id="cnblogs_post_body">wpf设置
1.给主程序类添加标签特性: [System.Runtime.InteropServices.ComVisible(true)]
如: [System.Runtime.InteropServices.ComVisible(true)]
public partial class MainWindow : Window
2.定义webbrowser导向网址:
webMain.Navigate(@"http://10.0.0.86:81");
webMain.Navigate(new Uri(@"E:\visual studio 2012\ShineHATMV1.0\WpfApp\testInterface.html", UriKind.RelativeOrAbsolute));
3.从wpf推送的页面函数及参数
webMain.Dispatcher.Invoke(new Action(() => { webMain.ObjectForScripting = this; webMain.InvokeScript("funName",new object[]{"paras"}); }));
方法名称:funName,参数:paras 页面中必须有同名同类型的参数;
4.从页面js调用wpf方法 页面js调用
window.external.CallBll("test");
wpf中: 需要提前定义好一个 接受类
//前台js调用后台js方法
[System.Runtime.InteropServices.ComVisible(true)]
public class JSCallBack{}
在初始化一下 这个类
JSCallBack jscall = new JSCallBack(this);
webMain.ObjectForScripting = jscall;
在类中定义好接收方法
//前台调用方法
public string CallBll(string type){}
5.注意 wpf 需在 webbrowser的LoadCompleted 事件执行之后才能使用 js 与 wpf 的相互之间的调用,winform没有验证
详细代码:
wpf:
<div class="cnblogs_code" > View Code <div id="cnblogs_code_open_3694b2e9-6c4f-4fda-94df-f713e4faa887" class="cnblogs_code_hide">namespace WpfApp{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> [System.Runtime.InteropServices.ComVisible(true)] public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); //webMain.Navigate(@"http://10.0.0.86:81"); webMain.Navigate(new Uri(@"E:\visual studio 2012\ShineHATMV1.0\WpfApp\testInterface.html", UriKind.RelativeOrAbsolute)); } private void btrInCard_Click(object sender, RoutedEventArgs e) { CallBackEvent("bank"); } private void Button_Click_1(object sender, RoutedEventArgs e) { JSCallBack jscall = new JSCallBack(this); webMain.ObjectForScripting = jscall; } //向前台 推送方法 void CallBackEvent(string type) { //function callbackEvent(isok, value, status, code, msg, fun) //isok:0 失败 1 成功 //type:bankPwd //value:bankNo:12345679,name:张三,ablance:500 //msg:提示信息 switch (type) { case "test": webMain.Dispatcher.Invoke(new Action(() => { webMain.ObjectForScripting = this; webMain.InvokeScript("test"); })); break; case "bank": webMain.Dispatcher.Invoke(new Action(() => { webMain.ObjectForScripting = this; webMain.InvokeScript("callbackEvent", new object[] { 1, "bankPwd", "bankNo:6221881900006135513$$bankName:农业银行", "" }); })); break; default: break; } } } //前台js调用后台js方法 [System.Runtime.InteropServices.ComVisible(true)] public class JSCallBack { MainWindow mainWindow; public JSCallBack(MainWindow main) { mainWindow = main; } //前台调用方法 public string CallBll(string type, int isOk, string paras) { switch (type) { case "inputBankPwd": break; case "bank": break; default: break; } return "test"; } }} |
|