简体   繁体   中英

Running a function once in DocumentCompleted

What i am trying to do is run a function once in a DocumentCompleted event, i know it will fire as many times as the browser loads in iframes / external links, i can't think of a way to do this.

What i have tried:

Code:

        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            bool hasFiredOnce = false;
            if ((sender as WebBrowser).ReadyState == WebBrowserReadyState.Complete)
            {
                try
                {
                    // 1) - Find out what url we are viewing and update accordingly ...
                    WebBrowser browser = (WebBrowser)sender;
                    var current_url = browser.Url.AbsoluteUri;
                    txtBoxUrl.Text = current_url;

                    // Check for any saved answers ...
                    if (hasFiredOnce == false) 
                    {
                        if (Helpers.CheckForSavedAnswers(txtBoxUrl.Text) != "NONE")
                        {
                            hasFiredOnce = true;
                            linkLabelAnswerText.Text = "Stored answer found!";
                            Helpers.ReturnMessage(Helpers.CheckForSavedAnswers(txtBoxUrl.Text));
                        }
                        else
                        {
                            linkLabelAnswerText.Text = "...";
                            hasFiredOnce = false;
                        }
                        Helpers.ReturnMessage("This should fire once!");
                     }
                }
                catch (Exception ex)
                {
                    Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
                }
            }
        }

Is to set a bool, if it is false we run the function Helpers.CheckForSavedAnswers(txtBoxUrl.Text) then set it to true so it won't run again, but it does, i think i am missing something obviously small here, any help would be appreciated.

I agree with Michael, the problem is that HasFiredOnce is declared and initialised inside the function you are trying to control. Make it a global variable, or store it somewhere else (eg in a database or file) that can be accessed globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM