2017-04-27 48 views
-1

我和上次有类似的问题,但无论我撞到墙上多少头,解决方案都不会来。问题是消息框创建次数太多,应该只打开一次,取消订阅documentCompleted然后退出。再次感谢!{again} C#MessageBox创建不止一次

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

    } 
} 

回答

4

您需要任何设置timer1.Enabled为假或致电timer1.Stop(),只要你进入timer1_Tick_1方法,或计时器将持续开火,每次调用你的方法。

+0

你我的朋友是天才:)。小心解释为什么会发生这种情况? – Nanyo

+0

当然,基本上,当你启动()或启用计时器时,计时器会一直闪烁,直到你选择停止。我发现你在GetImg方法中使用了“Dispose”,但是,GetImg只会在DocumentCompleted上调用(这可能会在开始下载后发生很多时间),并且定时器可能会在两次之间触发(因此会调用timer1_Tick_1方法多次)。这有帮助吗? –

+0

我看到谢谢,标记为已解决:) – Nanyo