C#实现的给IE浏览器添加右键快捷菜单项并将本页URL地址传递给右键菜单项所指向的外部应用程序

  将网页保存为mht格式其实是个很简单的功能,其实浏览器本身就带这个功能。这里只是利用这个简单的例子来介绍给IE浏览器添加右键快捷菜单功能项的,并将本页面的URL地址传给右键快捷菜单项所指向的应用程序并执行的过程。

  1、首先介绍给IE浏览器添加右键快捷菜单项,代码如下:

 1       try {
2 string regkey = @"Software\Microsoft\Internet Explorer\MenuExt\KnowledgeSave";
3 string scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"getcurrenturl.htm");
4 RegistryKey root = Registry.CurrentUser.OpenSubKey(regkey);
5
6 if (null == root)
7 {
8 root = Registry.CurrentUser.CreateSubKey(regkey);
9 root.SetValue("", scriptPath, RegistryValueKind.String);
10 root.SetValue("Contexts", 0x000000f3, RegistryValueKind.DWord);
11 }
12
13 } catch (Exception ex)
14 {
15 //DFApp.LogDebug(ex.ToString());
16 }

其中,添加的右键菜单项叫KnowledgeSave(第2行),这个将会出现在IE浏览器的右键菜单中,当点击着个菜单项后将指向“getcurrenturl.htm”。这个文件包含了获取本页URL地址并调用外部程序的javascript代码。

2、getcurrenturl.htm文件内容如下:

<script language="javascript">

    function exec(command) {
        window.oldOnError = window.onerror;

        window._command = command;
                
        window.onerror = function (err) {
            if (err.indexOf('utomation') != -1) {
                alert('命令' + window._command + ' 已经被用户禁止!');
                return true;
            }
            else return false;
        };
        var wsh = new ActiveXObject('WScript.Shell');
        if (wsh)
            wsh.Run(command);
        window.onerror = window.oldOnError;
    }

    function OnContextMenu() {
        var command = "D:/myProject/VS2010Project/wfaKnowledgeWarehouse/wfaKnowledgeWarehouse/bin/Debug/wfaKnowledgeWarehouse.exe ";
        var url = external.menuArguments.document.URL;
        exec(command + url);
    }

    OnContextMenu();
</script>

  本文件中定义了两个函数,第一个函数exec(command),负责将命令command在windows的cmd中执行;第二个函数OnContextMenu()负责获得当前页面的URL地址,并指出需要调用的外部执行程序的地址(这里我用的是绝对地址,大家可以根据需要改成相对的,这里就不多说了),并形成cmd下的命令语句交与exec函数执行。

  如上面代码,OnContextMenu()函数中的变量command指出了需要执行的外部程序是wfaKnowledgeWarehouse.exe,变量url获得了当前页面的URL地址。

  3、下面是wfaKnowledgeWarehouse的源码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using SmartKernel.Framework.Net.HtmlParser;
using SmartKernel.Framework.Net;
using SmartKernel.Framework.Log;
namespace wfaKnowledgeWarehouse
{
public class Program
{
static void Main(string[] args)
{
string strUrl = "";
if(args.Length>0)
{
strUrl = args[0];
}
try
{
DownLoader.SaveToMhtFile(strUrl, "包含路径的另存为的名字");
}
catch (Exception ex)
{
Console.WriteLine("网页内容无法保存!");
}
}
}
}

上面的代码功能很简单,就不多说了。其中包含了几个外部的dll文件

至此就完成了,请大家多多批评!

posted on 2011-09-27 21:38  飞云  阅读(2767)  评论(4编辑  收藏  举报

导航