Question

The problem is: When I remove the first message box line, my program doesn't run and throws "Exception has been thrown by the target of an invocation" on the if statement line. However, when I leave the messagebox there, it runs fine. Can someone explain to me why this is happening and what I can do to fix it? I'm fairly new to WPF by the way, any help would be appreciated.

public BrowserMode() {

       InitializeComponent();

       MessageBox.Show("Entering Browser Mode");
       if (webBrowser1.Source.Scheme == "http")
       {
           //cancel navigation
           //this.NavigationService.Navigating += new NavigatingCancelEventHandler(Cancel_Navigation);

           qd = new QuestionData();

           // code where stuff happens
           var url = webBrowser1.Source;
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

           // from h.RequestUri = "webcam://submit?question_id=45"
           var parseUrl = request.RequestUri; //the uri that responded to the request.
           MessageBox.Show("The requested URI is: " + parseUrl);
Was it helpful?

Solution

This sort of work is not suited for a constructor and should be moved out until after the WebBrowser is fully loaded. You have two options:

  1. Hook Control.Loaded and perform this behavior there.

    public BrowserMode()
    {
        InitializeComponent();
    
        this.Loaded += BroswerMode_Loaded;
    }
    
    void BrowserMode_Loaded(object sender, EventArgs e)
    {
        if (webBrowser1.Source != null
         && webBrowser1.Source.Scheme == "http")
        {
            qd = new QuestionData();
            // ...
        }
    }
    
  2. Hook WebBrowser.Navigating and perform this behavior there.

    public BrowserMode()
    {
        InitializeComponent();
    
        this.webBrowser1.Navigating += WebBrowser_Navigating;
    }    
    
    void WebBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (e.Uri.Scheme == "http")
        {
            qd = new QuestionData();
            // ...
        }
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top