Search code examples
c#formswinformsmessagebox

{again} C# MessageBox created more than once


I have a similar question as last time, but no matter how much I hit my head against the wall, solution is not coming. The problem is that the message box gets created too many times, when it should only open once, unsubscribe from documentCompleted and then exit. Thanks again!

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;
            }
        }

    }
}

Solution

  • You need to either set timer1.Enabled to false or call timer1.Stop() as soon as you enter the timer1_Tick_1 method, or the timer will keep firing and calling your method every time.