Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么登录网页不是';在webBrowser中没有显示?_C#_Winforms_Authentication_Webbrowser Control - Fatal编程技术网

C# 为什么登录网页不是';在webBrowser中没有显示?

C# 为什么登录网页不是';在webBrowser中没有显示?,c#,winforms,authentication,webbrowser-control,C#,Winforms,Authentication,Webbrowser Control,我正在使用C#登录本地网页。 我使用webBrowser在日志后显示页面。 首先,我导航到页面,然后填写用户名和密码,然后调用单击;所以我假设点击发生了。但是结果页面没有显示,执行时没有显示任何内容。 我试过这个: public WebBrowser webBrowser; public MainWindow() { InitializeComponent(); webBrowser = new

我正在使用C#登录本地网页。 我使用webBrowser在日志后显示页面。 首先,我导航到页面,然后填写用户名和密码,然后调用单击;所以我假设点击发生了。但是结果页面没有显示,执行时没有显示任何内容。 我试过这个:

        public WebBrowser webBrowser;

        public MainWindow()
        {
            InitializeComponent();

            webBrowser = new WebBrowser();

            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(LoginEvent);

            webBrowser.AllowNavigation = true;

            webBrowser.Navigate("http://192.168.1.100/login.html");
        }


         private void LoginEvent(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            WebBrowser webBrowser = sender as WebBrowser;

            //To execute the event just one time
            webBrowser.DocumentCompleted -= LoginEvent;


            //load page's document
            HtmlDocument doc = webBrowser.Document;

            doc.GetElementById("u").SetAttribute("value", "admin");

            doc.GetElementById("pw").SetAttribute("value", "123456");

            foreach (HtmlElement elem in doc.GetElementsByTagName("a"))
            {
                elem.InvokeMember("click");
            }
        }

有人能帮我弄清楚为什么页面没有显示吗?

1)您的
WebBrowser
对象是
MainWindow()
构造函数中的局部变量

一旦
主窗口
构造函数结束,此对象将被撤销

您需要将
WebBrowser
对象声明为类成员

2) 可能会触发多个
DocumentComplete
事件。您需要过滤掉所有iFrame事件并等待页面完全加载:

private void LoginEvent(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // filter out non main documents
    if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
        return; 

    //To execute the event just one time
    webBrowser.DocumentCompleted -= LoginEvent;

    //load page's document
    HtmlDocument doc = webBrowser.Document;

    doc.GetElementById("u").SetAttribute("value", "admin");

    doc.GetElementById("pw").SetAttribute("value", "123456");

    foreach (HtmlElement elem in doc.GetElementsByTagName("a"))
    {
        elem.InvokeMember("click");
    }
}

感谢您的回答,但它不起作用,我试图将其声明为字段,但没有任何更改。它也不起作用,我添加到您的更新代码
等待任务中。延迟(5000)在加载文档之前,但仍然不起作用。顺便说一句,非常感谢您花时间查看我的代码。