{again} C# MessageBox 创建了不止一次

{again} C# MessageBox created more than once

我和上次有类似的问题,但是无论我怎么用头撞墙,都没有解决方案。问题是消息框被创建了太多次,当它应该只打开一次时,取消订阅 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;
            }
        }

    }
}

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