微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 阻止显示Windows安全窗口

我有一些路由器配置页面URL,我必须加载它们,设置并保存它.我正在使用webbrowser控件和.Net 4.5和C#语言.但每次加载页面时,都会弹出 Windows安全性并要求输入用户名和密码.它适用于每个URL.我怎么能阻止这个?所有URL的用户名和密码都相同.如何使用硬编码为所有这些设置用户名和密码?!

解决方法

您需要通过 IServiceProvider向Webbrowser对象提供 IAuthenticate COM接口的实现.当Webbrowser处理需要Basic或Windows身份验证的资源时,将调用IAuthenticate :: Authenticate的实现,这样您就有机会提供正确的用户名和密码.

下面是如何通过Webbrowser的IProfferService完成此操作的完整示例.

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 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,Out,MarshalAs(UnmanagedType.LPWStr)] ref string pszUsername,MarshalAs(UnmanagedType.LPWStr)] ref string pszPassword);
        }
        #endregion
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐