JavaScript基础教程 WPF加载HTML、WPF与JavaScript交互
沉沙 2018-09-11 来源 : 阅读 1615 评论 0

摘要:本篇教程介绍了JavaScript基础教程 WPF加载HTML、WPF与JavaScript交互,希望阅读本篇文章以后大家有所收获,帮助大家对JavaScript的理解更加深入。

本篇教程介绍了JavaScript基础教程 WPF加载HTML、WPF与JavaScript交互,希望阅读本篇文章以后大家有所收获,帮助大家对JavaScript的理解更加深入。

<



一、WebBrowser加载远程网页

wbrExam.Source = new Uri("//cnblogs.com/sntetwt");

二、WebBrowser加载本地网页,注:不可以加载本地样式CSS和脚本JS文件

Uri uri = new Uri("pack://application:,,,/WPFSctipt;component/res/template.html", UriKind.Absolute);
Stream source = Application.GetResourceStream(uri).Stream;
wbrExam.NavigateToStream(source);

三、WebBrowser隐藏网页的JavaScript错误

this.wbrExam.SuppressScriptErrors(true);


 

/// <summary>
/// WebBrowser隐藏网页的JavaScript错误
/// </summary>
public static class WebBrowserExtensions
{
    public static void SuppressScriptErrors(this WebBrowser webBrowser, bool hide)
    {
        FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
        if (fiComWebBrowser == null) return;

        object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
        if (objComWebBrowser == null) return;

        objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
    }
}

四、网页屏蔽鼠标右键、Ctrl+N、Shift+F10、F11、F5刷新、退格键

<script type="text/javascript">
 //屏蔽鼠标右键、Ctrl+N、Shift+F10、F11、F5刷新、退格键     
 document.oncontextmenu = function(){event.returnValue=false;}//屏蔽鼠标右键     
 window.onhelp = function(){return   false}   //屏蔽F1帮助     
 document.onkeydown = function()
 {     
  if   ((window.event.altKey)&&     
                ((window.event.keyCode==37) ||       //屏蔽   Alt+   方向键   ←     
                (window.event.keyCode == 39))) {     //屏蔽   Alt+   方向键   →     
      event.returnValue = false;
      return false;
  }     
  /* 注:这还不是真正地屏蔽Alt+方向键,     
            因为Alt+方向键弹出警告框时,按住Alt键不放,     
            用鼠标点掉警告框,这种屏蔽方法就失效了。*/     
  if   ((event.keyCode==8) ||                                 //屏蔽退格删除键     
                (event.keyCode==116) ||                             //屏蔽   F5   刷新键     
                (event.ctrlKe && event.keyCode==82)) {              //Ctrl   +   R     
      event.keyCode=0;     
      event.returnValue=false;     
  }     
  if   (event.keyCode==122){event.keyCode=0;event.returnValue=false;}         //屏蔽F11     
  if   (event.ctrlKey && event.keyCode==78) event.returnValue=false;      //屏蔽Ctrl+n     
  if   (event.shiftKey && event.keyCode==121)event.returnValue=false;     //屏蔽shift+F10     
  if   (window.event.srcElement.tagName == "A" && window.event.shiftKey)       
      window.event.returnValue = false;                                   //屏蔽shift加鼠标左键新开一网页     
  if   ((window.event.altKey)&&(window.event.keyCode==115)){              //屏蔽Alt+F4     
      window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px");     
      return   false;     
  }     
 }     
</script>

五、WPF程序与网页JavaScript交互

public void Message(string str)
{
    MessageBox.Show(str);
}
/// <summary>
/// WebBrowser与JavaScript交互
/// </summary>
[System.Runtime.InteropServices.ComVisible(true)]
public class OprateBasic
{
    private MainWindow instance;
    public OprateBasic(MainWindow instance)
    {
        this.instance = instance;
    }
    //提供给JS调用
    public void HandleMessage(string p)
    {
        instance.Message(p);
    }
}
//CS调用JS
private void Button_Click(object sender, RoutedEventArgs e)
{
    this.wbrExam.InvokeScript("invokeScript", new object[] { "CS调用JS" });
}


  

JS调用CS
window.external.HandleMessage("JS调用CS");


  

//提供给CS调用
function invokeScript(args) {
            alert(args);
}

六、创建服务器,提供数据接口、Script、CSS文件
总结:因为加载HTML文件的时候,HTML没有路径,所以加载不了JS和CSS等外部文件
创建远程站点提供数据接口和外部文件
完整的CS程序如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;

namespace WPFSctipt
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            
            //加载远程网页
            //wbrExam.Source = new Uri("//cnblogs.com/sntetwt");

            Uri uri = new Uri("pack://application:,,,/WPFSctipt;component/res/template.html", UriKind.Absolute);
            Stream source = Application.GetResourceStream(uri).Stream;
            //WebBrowser隐藏网页的JavaScript错误
            this.wbrExam.SuppressScriptErrors(true);
            //WebBrowser与JavaScript交互
            this.wbrExam.ObjectForScripting = new OprateBasic(this);
            //加载本地HTML文件
            wbrExam.NavigateToStream(source);
        }
        public void Message(string str)
        {
            MessageBox.Show(str);
        }
        /// <summary>
        /// WebBrowser与JavaScript交互
        /// </summary>
        [System.Runtime.InteropServices.ComVisible(true)]
        public class OprateBasic
        {
            private MainWindow instance;
            public OprateBasic(MainWindow instance)
            {
                this.instance = instance;
            }
            //提供给JS调用
            public void HandleMessage(string p)
            {
                instance.Message(p);
            }
        }
        //CS调用JS
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.wbrExam.InvokeScript("invokeScript", new object[] { "CS调用JS" });
        }
    }
    /// <summary>
    /// WebBrowser隐藏网页的JavaScript错误
    /// </summary>
    public static class WebBrowserExtensions
    {
        public static void SuppressScriptErrors(this WebBrowser webBrowser, bool hide)
        {
            FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser == null) return;

            object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
            if (objComWebBrowser == null) return;

            objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
        }
    }
}


  
ASMX文件代码

<Window x:Class="WPFSctipt.MainWindow"
        xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="//schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF加载HTML、WPF与JavaScript交互" Height="600" Width="800" ContentRendered="Window_ContentRendered">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="500"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <WebBrowser Grid.Row="0" Name="wbrExam" Height="500" VerticalAlignment="Top" Width="800"/>
        <Button Grid.Row="1" Content="CS调用JS" VerticalAlignment="Top" Width="200" Height="40" Margin="10" Click="Button_Click" />
    </Grid>
</Window>


  
HTML代码

<!DOCTYPE html>
<html lang="en" xmlns="//www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=8" /> 
    <title></title>
    <style type="text/css">
        body{background:red;}
        .div{height:400px;}
    </style>
    <script type="text/javascript" src="//common.cnblogs.com/script/jquery.js"></script>
 <script type="text/javascript">
  //屏蔽鼠标右键、Ctrl+N、Shift+F10、F11、F5刷新、退格键     
  document.oncontextmenu = function(){event.returnValue=false;}//屏蔽鼠标右键     
  window.onhelp = function(){return   false}   //屏蔽F1帮助     
  document.onkeydown = function()
  {     
      if   ((window.event.altKey)&&     
                    ((window.event.keyCode==37) ||       //屏蔽   Alt+   方向键   ←     
                    (window.event.keyCode == 39))) {     //屏蔽   Alt+   方向键   →     
          event.returnValue = false;
          return false;
      }     
      /* 注:这还不是真正地屏蔽Alt+方向键,     
            因为Alt+方向键弹出警告框时,按住Alt键不放,     
            用鼠标点掉警告框,这种屏蔽方法就失效了。*/     
      if   ((event.keyCode==8) ||                                 //屏蔽退格删除键     
                    (event.keyCode==116) ||                             //屏蔽   F5   刷新键     
                    (event.ctrlKe && event.keyCode==82)) {              //Ctrl   +   R     
          event.keyCode=0;     
          event.returnValue=false;     
      }     
      if   (event.keyCode==122){event.keyCode=0;event.returnValue=false;}         //屏蔽F11     
      if   (event.ctrlKey && event.keyCode==78) event.returnValue=false;      //屏蔽Ctrl+n     
      if   (event.shiftKey && event.keyCode==121)event.returnValue=false;     //屏蔽shift+F10     
      if   (window.event.srcElement.tagName == "A" && window.event.shiftKey)       
          window.event.returnValue = false;                                   //屏蔽shift加鼠标左键新开一网页     
      if   ((window.event.altKey)&&(window.event.keyCode==115)){              //屏蔽Alt+F4     
          window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px");     
          return   false;     
      }     
  }     
 </script>
    <script type="text/javascript">
        $(function () {
            $("div").text("JavaScript被执行");
            window.external.HandleMessage("JS调用CS");
        })
        function invokeScript(args) {
            alert(args);
        }
    </script>
</head>
<body>
    <div class="div"></div>
</body>
</html>


   

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端JavaScript频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程