I have a button that navigates a web page. I was trying to put the navigation in a backgroundworker, but it doesn't navigate. If I put it in the click event of the button it works fine. I put a break point in the bgw_DoWork and it shows that it hits the point of creating a new wb object, however it skips the rest of the statements in the DoWork. I wanted to do this so that I can display a loading image while it is trying to get data from a web page. The webbrowser object is not part of the UI as the user doesn't need to see the scraping. It just downloads the information into an object and then later displays the object (outside of the BackgroundWorker).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
using System.ComponentModel;
using mshtml;
namespace WPF1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
WebBrowser wb;
private readonly BackgroundWorker bgw = new BackgroundWorker();
public int i = 0;
public MainWindow()
{
InitializeComponent();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
}
private void GetSICData_Click(object sender, RoutedEventArgs e)
{
//mainTabControl.SelectedIndex = 1;
//wb.Navigated += wb_Navigated;
//wb.LoadCompleted += wb_LoadCompleted;
//wb.Navigate("http://www.google.com");
bgw.RunWorkerAsync();
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
wb = new WebBrowser();
wb.Navigated += wb_Navigated;
wb.LoadCompleted += wb_LoadCompleted;
wb.Navigate("http://www.google.com");
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Background Complete");
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
HTMLDocument doc = (HTMLDocument)wb.Document;
doc.getElementById("ctl03_TextBox1").innerText = "2334882";
wb.LoadCompleted -= wb_LoadCompleted;
wb.LoadCompleted += wb_LoadCompleted_2;
doc.getElementById("ImageButton1").click();
}
void wb_LoadCompleted_2(object sender, NavigationEventArgs e)
{
MessageBox.Show("It Worked!");
}
void wb_Navigated(object sender, NavigationEventArgs e)
{
}
}
}