简体   繁体   English

在 DocumentCompleted 中运行一次 function

[英]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.我想要做的是在 DocumentCompleted 事件中运行一次 function,我知道它会在浏览器加载 iframe/外部链接时触发多次,我想不出办法来做到这一点。

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.是设置一个布尔值,如果它是false的,我们运行 function Helpers.CheckForSavedAnswers(txtBoxUrl.Text)然后将其设置为true ,这样它就不会再次运行,但确实如此,我想我在这里遗漏了一些明显很小的东西,任何帮助将不胜感激。

I agree with Michael, the problem is that HasFiredOnce is declared and initialised inside the function you are trying to control.我同意迈克尔的观点,问题是 HasFiredOnce 在您试图控制的 function 中被声明和初始化。 Make it a global variable, or store it somewhere else (eg in a database or file) that can be accessed globally.使其成为全局变量,或将其存储在可以全局访问的其他位置(例如,在数据库或文件中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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