码迷,mamicode.com
首页 > 编程语言 > 详细

在webBrowser中触发html页面中的javaScript.

时间:2015-04-14 16:28:53      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

实例的功能是把一个图片加到html的img tag中。

You can encode the image in base64. For example

<img src="data:image/gif;base64,MyImageDataEncodedInBase64
="
alt="My Image data in base 64" />

Here is a full example of how you can accomplish this:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ImageEncodedInBase64InAWebBrowser
{
    [ComVisible(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string url = Directory.GetCurrentDirectory() + "\\page.html";
            webBrowser1.Url = new Uri(url);
            webBrowser1.ObjectForScripting = this;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string imageInBase64 = ReadImageInBase64();
            webBrowser1.Document.InvokeScript("setImageData", new[] { imageInBase64 });

        }

        private string ReadImageInBase64()
        {
            string imagePath = Directory.GetCurrentDirectory() + "\\opensource.png";
            using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                return Convert.ToBase64String(buffer);
            }
        }
    }
}

 

And this Javascript code:

function setImageData(imageBase64) {
    var myImg = document.getElementById("myImg");
    myImg.src = "data:image/png;base64," + imageBase64;
}

 

在webBrowser中触发html页面中的javaScript.

标签:

原文地址:http://www.cnblogs.com/tony-MSDN/p/4425114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!