最近開發winForm項目用到open-webkit-sharp,自己研究一下分享給大家。
開發環境:vs2017,OpenWebKitSharp 3.0.1.0023
1、首先要下載OpenWebKitSharp ,推薦去google下載(http://code.google.com/p/open-webkit-sharp/),github文件太多下載速度較慢;
2、新建一個winForm工程,將下載的openwebkitsharp文件解壓縮,
從open-webkit-sharp-master文件夾中把Core文件夾和References文件夾中的文件複製到Demo的Debug文件夾下
從Binary下把JSCore.dll,OpenWebKitSharp.dll,OpenWebKitSharp.manifest,WebKit.Interop.dll複製到Demo的Debug文件夾下,選擇替換(如果使用的是Framework2.0的框架則複製Binary NET2下面的文件)。
3、添加引用
4、在工具箱中添加webKitBrowser控件,在vs頂部的工具選項卡中,點擊“選擇工具箱項”,點擊“瀏覽”,在工程的debug目錄下找到OpenWebKitSharp.dll,點擊“打開”,然後點擊“確定”。之後再工具箱中找到webKitBrowser控件拖到form中,順便也拖個button,爲了後邊的交互做準備。
5、廢了這麼大的勁還沒有走到正道上,哇咔咔,乾糧終於來了。新建一個html文件,隨便建一個div,添加一個帶有點擊事件的標籤,我這裏用image(這個是準備去調用C#的);
<img alt="" src="/image/home.png" style="height: 79px; width: 110px" onclick="window.external.Test('www.baidu.com'); return false" />
順便把C#調用JavaScript的代碼也寫過來:
function message(jsStr) {
eval(jsStr);
}
6、開始操作C#代碼,雙擊button添加點擊事件,說明一下,html文件中還需要有一個id是“text”的標籤;這個就是C#調用js的關鍵代碼;
private void button1_Click(object sender, EventArgs e)
{
webKitBrowser1.UseJavaScript = true;
string strScript = "messageBox(document.getElementById('text').innerText = '123456')";
webKitBrowser1.StringByEvaluatingJavaScriptFromString(strScript);
}
7、js調用C#就稍稍麻煩一些,在Form設計裏雙擊webKitBrowser添加代碼。
private void webKitBrowser1_Load(object sender, EventArgs e)
{
webKitBrowser1.OpenDocument(AppDomain.CurrentDomain.BaseDirectory + "www/block_test_pc/async-execution.html");//路徑是在自己工程目錄bin/debug/www/...自己可以修改
webKitBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webKitBrowser1_DocumentCompleted);
webKitBrowser1.Dock = DockStyle.Fill;//充滿窗口
}
void webKitBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.webKitBrowser1.GetScriptManager.ScriptObject = new Form1();
}
public void Test(string msg)
{
MessageBox.Show("123456789");
}
大功告成,哇咔咔!!!
這只是實現了基本功能,歡迎交流學習。