C# 防止显示Windows安全窗口
我有一些路由器配置页面URL,我必须加载它们,设置并保存它。我正在使用webbrowser控件以及.NET4.5和C语言。但每次加载页面时,windows security都会弹出并要求输入用户名和密码。它发生在每个URL上。我怎样才能避免这种情况?所有URL的用户名和密码都相同。我如何使用硬代码为所有这些设置用户名和密码 我在微软的论坛上找到了这个:C# 防止显示Windows安全窗口,c#,.net,winforms,authentication,webbrowser-control,C#,.net,Winforms,Authentication,Webbrowser Control,我有一些路由器配置页面URL,我必须加载它们,设置并保存它。我正在使用webbrowser控件以及.NET4.5和C语言。但每次加载页面时,windows security都会弹出并要求输入用户名和密码。它发生在每个URL上。我怎样才能避免这种情况?所有URL的用户名和密码都相同。我如何使用硬代码为所有这些设置用户名和密码 我在微软的论坛上找到了这个: 您需要通过提供一个COM接口到WebBrowser对象的实现。当WebBrowser处理需要基本身份验证或Windows身份验证的资源时,将调用
您需要通过提供一个COM接口到
WebBrowser
对象的实现。当WebBrowser
处理需要基本身份验证或Windows身份验证的资源时,将调用IAuthenticate::Authenticate
的实现,使您有机会提供正确的用户名和密码
下面是如何通过WebBrowser
完成此操作的完整示例
使用Microsoft.Win32;
使用制度;
使用系统诊断;
使用系统线程;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Runtime.InteropServices;
命名空间WebBrowserAuthApp
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
公共部分类主窗体:窗体,
ComExt.IServiceProvider,
ComExt.IAuthenticate
{
网络浏览器;
uint\u authenticateServiceCookie=ComExt.INVALID;
ComExt.IProfferService _profferService=null;
CancellationTokenSource _navigationCts=null;
任务_navigationTask=null;
公共表格(
{
SetBrowserFeatureControl();
初始化组件();
InitBrowser();
这个.Load+=(s,e)=>
{
_navigationCts=新的CancellationTokenSource();
_navigationTask=DoNavigationAsync(_navigationCts.Token);
};
}
//创建WebBrowser实例(可以使用现有实例)
void InitBrowser()
{
this.webBrowser=新的webBrowser();
this.webBrowser.Dock=DockStyle.Fill;
this.Controls.Add(this.webBrowser);
this.webBrowser.Visible=true;
}
//主要导航任务
异步任务DoNavigationAsync(取消令牌ct)
{
//首先导航到空白页以初始化webBrowser.ActiveXInstance
等待导航同步(ct,“关于:空白”);
//通过IProfferService将IAuthenticate设置为服务
var ax=this.webBrowser.ActiveXInstance;
var serviceProvider=(ComExt.IServiceProvider)ax;
服务提供者。查询服务(外部提供服务);
_profferService.profferService(typeof(ComExt.iaauthenticate).GUID,this,ref\u authenticateServiceCookie);
//导航到需要基本身份验证的网站
//例如:http://www.httpwatch.com/httpgallery/authentication/
字符串html=等待导航同步(ct,“http://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx");
MessageBox.Show(html);
}
//异步导航
异步任务NavigateAsync(CancellationToken ct,字符串url)
{
var onload tcs=new TaskCompletionSource();
EventHandler onloadEventHandler=null;
WebBrowserDocumentCompletedEventHandler documentCompletedHandler=委托
{
//对于同一页,DocumentCompleted可以多次调用,
//由于框架
if(onloadEventHandler!=null | | onloadTcs==null | | onloadTcs.Task.IsCompleted)
返回;
//处理DOM onload事件以确保文档已完全加载
onloadEventHandler=(s,e)=>
onload tcs.TrySetResult(真);
this.webBrowser.Document.Window.AttachEventHandler(“onload”,onloadEventHandler);
};
尝试
{
this.webBrowser.DocumentCompleted+=documentCompletedHandler;
使用(ct.Register(()=>onload tcs.trysetconceled(),useSynchronizationContext:true))
{
this.webBrowser.Navigate(url);
//等待DOM onload,如果取消则抛出
等待onload任务;
}
}
最后
{
this.webBrowser.DocumentCompleted-=documentCompletedHandler;
if(onloadEventHandler!=null)
this.webBrowser.Document.Window.DetachEventHandler(“onload”,onloadEventHandler);
}
返回此.webBrowser.Document.GetElementsByTagName(“html”)[0].OuterHtml;
}
//关闭
关闭时受保护的覆盖无效(事件参数e)
{
如果(_navigationCts!=null&&u navigationCts!=null&&u navigationTask.IsCompleted)
{
_navigationCts.Cancel();
_navigationCts.Dispose();
_navigationCts=null;
}
if(_authenticateServiceCookie!=comText.INVALID)
{
_profferService.RevokeService(_authenticateServiceCookie);
_authenticateServiceCookie=ComExt.INVALID;
发布对象(提供服务);
_profferService=null;
}
}
#区域ComExt.IServiceProvider
public int QueryService(ref Guid guidService、ref Guid riid、ref IntPtr ppvObject)
{
if(guidService==typeof(ComExt.IAuthenticate.GUID)
{
返回这个.QueryInterface(ref-riid,ref-ppvObject);
}
返回ComExt.E_NOINTERFACE;
}
#端区
#区域ComExt.IAuthenticate
公共int身份验证(ref IntPtr phwnd,ref string pszUsername,ref string
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WebBrowserAuthApp
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public partial class MainForm : Form,
ComExt.IServiceProvider,
ComExt.IAuthenticate
{
WebBrowser webBrowser;
uint _authenticateServiceCookie = ComExt.INVALID;
ComExt.IProfferService _profferService = null;
CancellationTokenSource _navigationCts = null;
Task _navigationTask = null;
public MainForm()
{
SetBrowserFeatureControl();
InitializeComponent();
InitBrowser();
this.Load += (s, e) =>
{
_navigationCts = new CancellationTokenSource();
_navigationTask = DoNavigationAsync(_navigationCts.Token);
};
}
// create a WebBrowser instance (could use an existing one)
void InitBrowser()
{
this.webBrowser = new WebBrowser();
this.webBrowser.Dock = DockStyle.Fill;
this.Controls.Add(this.webBrowser);
this.webBrowser.Visible = true;
}
// main navigation task
async Task DoNavigationAsync(CancellationToken ct)
{
// navigate to a blank page first to initialize webBrowser.ActiveXInstance
await NavigateAsync(ct, "about:blank");
// set up IAuthenticate as service via IProfferService
var ax = this.webBrowser.ActiveXInstance;
var serviceProvider = (ComExt.IServiceProvider)ax;
serviceProvider.QueryService(out _profferService);
_profferService.ProfferService(typeof(ComExt.IAuthenticate).GUID, this, ref _authenticateServiceCookie);
// navigate to a website which requires basic authentication
// e.g.: http://www.httpwatch.com/httpgallery/authentication/
string html = await NavigateAsync(ct, "http://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx");
MessageBox.Show(html);
}
// asynchronous navigation
async Task<string> NavigateAsync(CancellationToken ct, string url)
{
var onloadTcs = new TaskCompletionSource<bool>();
EventHandler onloadEventHandler = null;
WebBrowserDocumentCompletedEventHandler documentCompletedHandler = delegate
{
// DocumentCompleted may be called several time for the same page,
// beacuse of frames
if (onloadEventHandler != null || onloadTcs == null || onloadTcs.Task.IsCompleted)
return;
// handle DOM onload event to make sure the document is fully loaded
onloadEventHandler = (s, e) =>
onloadTcs.TrySetResult(true);
this.webBrowser.Document.Window.AttachEventHandler("onload", onloadEventHandler);
};
try
{
this.webBrowser.DocumentCompleted += documentCompletedHandler;
using (ct.Register(() => onloadTcs.TrySetCanceled(), useSynchronizationContext: true))
{
this.webBrowser.Navigate(url);
// wait for DOM onload, throw if cancelled
await onloadTcs.Task;
}
}
finally
{
this.webBrowser.DocumentCompleted -= documentCompletedHandler;
if (onloadEventHandler != null)
this.webBrowser.Document.Window.DetachEventHandler("onload", onloadEventHandler);
}
return this.webBrowser.Document.GetElementsByTagName("html")[0].OuterHtml;
}
// shutdown
protected override void OnClosed(EventArgs e)
{
if (_navigationCts != null && _navigationCts != null && !_navigationTask.IsCompleted)
{
_navigationCts.Cancel();
_navigationCts.Dispose();
_navigationCts = null;
}
if (_authenticateServiceCookie != ComExt.INVALID)
{
_profferService.RevokeService(_authenticateServiceCookie);
_authenticateServiceCookie = ComExt.INVALID;
Marshal.ReleaseComObject(_profferService);
_profferService = null;
}
}
#region ComExt.IServiceProvider
public int QueryService(ref Guid guidService, ref Guid riid, ref IntPtr ppvObject)
{
if (guidService == typeof(ComExt.IAuthenticate).GUID)
{
return this.QueryInterface(ref riid, ref ppvObject);
}
return ComExt.E_NOINTERFACE;
}
#endregion
#region ComExt.IAuthenticate
public int Authenticate(ref IntPtr phwnd, ref string pszUsername, ref string pszPassword)
{
phwnd = IntPtr.Zero;
pszUsername = "httpwatch";
pszPassword = String.Empty;
return ComExt.S_OK;
}
#endregion
// Browser version control
// http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation
private void SetBrowserFeatureControl()
{
// FeatureControl settings are per-process
var fileName = System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
// make the control is not running inside Visual Studio Designer
if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0)
return;
// Webpages containing standards-based !DOCTYPE directives are displayed in IE9/IE10 Standards mode.
SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", fileName, 9000);
}
private void SetBrowserFeatureControlKey(string feature, string appName, uint value)
{
// http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx
using (var key = Registry.CurrentUser.CreateSubKey(
String.Concat(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\", feature),
RegistryKeyPermissionCheck.ReadWriteSubTree))
{
key.SetValue(appName, (UInt32)value, RegistryValueKind.DWord);
}
}
}
// COM interfaces and helpers
public static class ComExt
{
public const int S_OK = 0;
public const int E_NOINTERFACE = unchecked((int)0x80004002);
public const int E_UNEXPECTED = unchecked((int)0x8000ffff);
public const int E_POINTER = unchecked((int)0x80004003);
public const uint INVALID = unchecked((uint)-1);
static public void QueryService<T>(this IServiceProvider serviceProvider, out T service) where T : class
{
Type type = typeof(T);
IntPtr unk = IntPtr.Zero;
int result = serviceProvider.QueryService(type.GUID, type.GUID, ref unk);
if (unk == IntPtr.Zero || result != S_OK)
throw new COMException(
new StackFrame().GetMethod().Name,
result != S_OK ? result : E_UNEXPECTED);
try
{
service = (T)Marshal.GetTypedObjectForIUnknown(unk, type);
}
finally
{
Marshal.Release(unk);
}
}
static public int QueryInterface(this object provider, ref Guid riid, ref IntPtr ppvObject)
{
if (ppvObject != IntPtr.Zero)
return E_POINTER;
IntPtr unk = Marshal.GetIUnknownForObject(provider);
try
{
return Marshal.QueryInterface(unk, ref riid, out ppvObject);
}
finally
{
Marshal.Release(unk);
}
}
#region IServiceProvider Interface
[ComImport()]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
[PreserveSig]
int QueryService(
[In] ref Guid guidService,
[In] ref Guid riid,
[In, Out] ref IntPtr ppvObject);
}
#endregion
#region IProfferService Interface
[ComImport()]
[Guid("cb728b20-f786-11ce-92ad-00aa00a74cd0")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IProfferService
{
void ProfferService(ref Guid guidService, IServiceProvider psp, ref uint cookie);
void RevokeService(uint cookie);
}
#endregion
#region IAuthenticate Interface
[ComImport()]
[Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAuthenticate
{
[PreserveSig]
int Authenticate([In, Out] ref IntPtr phwnd,
[In, Out, MarshalAs(UnmanagedType.LPWStr)] ref string pszUsername,
[In, Out, MarshalAs(UnmanagedType.LPWStr)] ref string pszPassword);
}
#endregion
}
}
Uri u = new Uri("http://your_domain");
UriBuilder ub = new UriBuilder(u);
ub.UserName = "username";
ub.Password = "password";
webBrowser1.Url = ub.Uri;