从列表中导航 Web 浏览器

本文关键字:Web 浏览器 导航 列表 | 更新日期: 2023-09-27 18:32:13

当我启动这个程序时,我只 http://www.google.com 进入消息框,但是我应该得到 http://www.yahoo.com,然后 http://www.google.com。那么,问题出在哪里呢?那么,你能帮我解决这个问题吗?谢谢:)

有一个 XAML 代码:

<Window x:Class="WpfApplication19.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="800" Width="800">
<Grid Name="grid">
    <Button Name="btn" Content="Navigate" HorizontalAlignment="Left" Margin="697,223,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
    <Button Name="shower" Content="getValues" HorizontalAlignment="Left" Margin="697,262,0,0" VerticalAlignment="Top" Width="75" Click="shower_Click"/>
</Grid></Window>

还有 C# 短代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using mshtml;
namespace WpfApplication19
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<string> list = new List<string>();
        private List<string> arrOfAdresses = new List<string>();
        private WebBrowser thisIsWeb;
        public MainWindow()
        {
            InitializeComponent();
            list.Add("http://www.yahoo.com");
            list.Add("http://www.google.com");
            thisIsWeb = new WebBrowser();
            thisIsWeb.Width = thisIsWeb.Height = 400;
            this.grid.Children.Add(thisIsWeb);
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in list)
            {
                thisIsWeb.Navigate(s);
                thisIsWeb.LoadCompleted += OnthisIsWebCompleted;
            }
        }
        private void OnthisIsWebCompleted(object sender, NavigationEventArgs e)
        {
            WebBrowser bro = sender as WebBrowser;
            this.arrOfAdresses.Add(bro.Source.ToString());
        }
        private void shower_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in arrOfAdresses)
                MessageBox.Show(s);
        }
    }
}

从列表中导航 Web 浏览器

很简单:

您正在使用LoadCompleted来填充arrOfAdresses 。调用导航并不能保证LoadCompleted被调用! LoadCompleted - 顾名思义 - 一旦加载您导航到的页面,就会调用。

由于您紧接着导航到两个不同的 URL,因此只有对 Navigate最后一次调用才会真正导致网站加载 - 之前的导航被下一次调用 Navigate 隐式"中止"。

因此,唯一成功加载(因此提高LoadCompleted)的网站是http://www.google.com