C#在IE右键菜单中添加自定义项的实现代码

发布时间:2020-10-07编辑:脚本学堂
如何用C#实现在IE右键菜单中添加自定义项呢?本文为大家介绍一个实现方法,并附有实例代码,供大家学习参考。

首先,增加注册表项 HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMenuExtMyApp
MyApp为要显示在右键菜单中的名称
VBScript处理脚本,新增的注册表项的默认值是包含这个VBScript脚本的Html页面地址。

1、添加注册表项:
 

/// <summary>
/// 在IE中增加右键菜单
/// </summary>
static void RegistryIeContextMenu() {
try {
string regkey = @"SoftwareMicrosoftInternet ExplorerMenuExtMyApp";
string scriptPath = Path.Combine(AppDomain.CurrentDomain.Basedirectory, "geturl.htm");
RegistryKey root = Registry.CurrentUser.OpenSubKey(regkey);
if (null == root) {
root = Registry.CurrentUser.CreateSubKey(regkey);
root.SetValue("", scriptPath, RegistryValueKind.String);
root.SetValue("Contexts", 0x00000022, RegistryValueKind.DWord);
}
} catch (Exception ex) {
DFApp.LogDebug(ex.ToString());
}
}

2、脚本geturl.htm
 

复制代码 代码示例:

<script language="VBScript">
Sub AddLink(Url,Info,Location)
On Error Resume Next

if Url <> "" then
if Info = "" then
Info = "unknown"
end if
if Len(Info) > 1000 then
Info = Left(Info, 1000)
end if

DownloadInfo = Url "^" Info
set shell = CreateObject("Wscript.Shell")

shell.Run "C:MyApp.EXE " DownloadInfo

end if
end sub

Sub OnContextMenu()

set srcEvent = external.menuArguments.event
set srcLocation = external.menuArguments.location
set EventElement = external.menuArguments.document.elementFromPoint ( srcEvent.clientX, srcEvent.clientY )
if srcEvent.type = "MenuExtAnchor" then
set srcAnchor = EventElement
do until TypeName(srcAnchor)="HTMLAnchorElement"
set srcAnchor=srcAnchor.parentElement
Loop
Call AddLink(srcAnchor.href,srcAnchor.innerText,srcLocation)
elseif srcEvent.type="MenuExtImage" then
if TypeName(EventElement)="HTMLAreaElement" then
Call AddLink(EventElement.href,EventElement.Alt,srcLocation)
else
set srcImage = EventElement
set srcAnchor = srcImage.parentElement
do until TypeName(srcAnchor)="HTMLAnchorElement"
set srcAnchor=srcAnchor.parentElement
if TypeName(srcAnchor)="Nothing" then
call AddLink(srcImage.href,srcImage.Alt,srcLocation)
exit sub
end if
Loop
Call AddLink(srcAnchor.href,srcImage.Alt,srcLocation)
end if
elseif srcEvent.type="MenuExtUnknown" then
set srcAnchor = EventElement
do until TypeName(srcAnchor)="HTMLAnchorElement"
set srcAnchor=srcAnchor.parentElement
if TypeName(srcAnchor)="Nothing" then
Call AddLink(EventElement.href,EventElement.innerText,srcLocation)
exit sub
end if
Loop
Call AddLink(srcAnchor.href,srcAnchor.innerText,srcLocation)
elseif 1=1 then
MsgBox("Unknown Event Source """ srcEvent.type """" vbCrLf "Please send description of error to test@jb200.com")
end if
end sub

call OnContextMenu()
</script>