【问题标题】:{again} C# MessageBox created more than once{again} C# MessageBox 创建了不止一次
【发布时间】:2017-04-27 01:07:21
【问题描述】:

我有一个与上次类似的问题,但无论我如何将头撞到墙上,解决方案都不会出现。问题是消息框被创建太多次,当它应该只打开一次时,取消订阅documentCompleted 然后退出。再次感谢!

private void textBox4_TextChanged(object sender, EventArgs e)
{
    if (textBox4.Text.Length >= 3)
    {
        timer1.Enabled = true;
    }
}

private void timer1_Tick_1(object sender, EventArgs e)
{
    if (textBox4.Text != "")
    {
        webBrowser1.ScriptErrorsSuppressed = true;
        webBrowser1.Navigate("https://worldofwarcraft.com/en-gb/search?q=" + textBox4.Text);

        webBrowser1.DocumentCompleted += GetImg; //sub here
    }
}

private void GetImg(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    string img_url = "";
    foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
    {
        if (el.GetAttribute("className") == "Avatar-image")
        {
            img_url = (el.OuterHtml).Substring(el.OuterHtml.IndexOf("https"));
            img_url = img_url.Substring(0, img_url.IndexOf(")"));
            pictureBox1.ImageLocation = img_url;
        }
        else if (el.GetAttribute("className") == "Character-level")
        {
            textBox5.Visible = true;
            label7.Visible = true;
            string lvl_url = "";
            lvl_url = (el.InnerHtml).Substring(3);
            lvl_url = lvl_url.Substring(0, lvl_url.IndexOf("<"));
            textBox5.Text = lvl_url;
            DialogResult YESNO = MessageBox.Show("Is this your character?", "Select your char", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (YESNO == DialogResult.Yes)
            {
                // clean up
                webBrowser1.DocumentCompleted -= GetImg; //unsub here
                pictureBox1.Enabled = false;
                timer1.Dispose();
                break;
            }
        }

    }
}

【问题讨论】:

    标签: c# forms winforms messagebox


    【解决方案1】:

    您需要将 timer1.Enabled 设置为 false 或在您进入 timer1_Tick_1 方法后立即调用 timer1.Stop(),否则计时器将继续触发并每次都调用您的方法。

    【讨论】:

    • 你我的朋友是个天才:)。愿意解释为什么会这样吗?
    • 当然,基本上,当您开始()或启用计时器时,计时器将永远触发,直到您选择停止它。我看到您在 GetImg 方法中使用了“Dispose”,但是,GetImg 只会在 DocumentCompleted 上调用(这可能会在您开始下载后很长时间内发生)并且计时器可以在两者之间触发多次(因此调用您的timer1_Tick_1 方法多次)。这有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2015-01-18
    • 2021-06-02
    相关资源
    最近更新 更多