C# 操作 IE 浏览器安全区域设置
由于公司项目主要接入银行支付,但是供应商只提供 OCX 的接入方式,开发的过程中发现必须要将公司的域名添加到受信任的站点区域,如下图。
为了减少用户的使用难度,我和同事商量能否通过代码把网址添加到注册表或者 IE 的受信任的站点中,最后在微软的 IE 博客中找到了解决办法。
首先定义了一个 IInternetSecurityManager 接口:
[ComImport, Guid("79EAC9EE-BAF9-11CE-8C82-00AA004BA90B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInternetSecurityManager { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int SetSecuritySite([In] IntPtr pSite); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int GetSecuritySite([Out] IntPtr pSite); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int MapUrlToZone([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out UInt32 pdwZone, UInt32 dwFlags); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int GetSecurityId([MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pbSecurityId, ref UInt32 pcbSecurityId, uint dwReserved); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int ProcessUrlAction([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, UInt32 dwAction, out byte pPolicy, UInt32 cbPolicy, byte pContext, UInt32 cbContext, UInt32 dwFlags, UInt32 dwReserved); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int QueryCustomPolicy([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, ref Guid guidKey, ref byte ppPolicy, ref UInt32 pcbPolicy, ref byte pContext, UInt32 cbContext, UInt32 dwReserved); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int SetZoneMapping(UInt32 dwZone, [In, MarshalAs(UnmanagedType.LPWStr)] string lpszPattern, UInt32 dwFlags); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int GetZoneMappings(UInt32 dwZone, out IEnumString ppenumString, UInt32 dwFlags); }
通过 Internet Security Manager COM 对象,并获取对 IInternetSecurityManager 接口的引用:
Type t = Type.GetTypeFromCLSID(CLSID_InternetSecurityManager); _securityManager = Activator.CreateInstance(t); _ism = (IInternetSecurityManager) _securityManager;
添加到指定的安全区域
int result = _ism.SetZoneMapping((UInt32)_ctrl.Tag, txtPattern.Text, SZM_CREATE); if (0 == result) { MessageBox.Show("Pattern \"" + txtPattern.Text + "\" successfully added to " + _ctrl.Text + " zone."); } else { MessageBox.Show("Could not add pattern \"" + txtPattern.Text + "\" to " + _ctrl.Text + " zone."); }
添加成功后就可以执行 ActiveX 控件了。
另外,有些电脑 IE 安全设置“对为标记为可安全执行脚本的 ActiveX 控件初始化并执行脚本”选项是禁用的,所以也需要改成启用才能执行。
代码下载:IESecurityZones