C#通知不断重复

时间:2019-04-12 19:43:42

标签: c# winforms notifications

我使用c#创建了一个hangman应用。现在,我希望您以错误的字母以及离开的机会得到通知。那行得通,但我的通知不断重复。我试图在通知后产生一个“中断”。但这不起作用。

这是我的代码

        private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            //status 1 van het galgje poppetje
            if (status >= 1)
            {
                //geeft notificatie nog 9 kansen
                notifyIcon1.BalloonTipText = "1 kans minder, je hebt nog 9 kansen";
                notifyIcon1.Icon = SystemIcons.Exclamation;
                notifyIcon1.ShowBalloonTip(1000);
                e.Graphics.DrawLine(new Pen(Color.Black, 2), 85, 190, 210, 190);
            }
            //status 2 van het galgje poppetje
            if (status >= 2)
            {
                //geeft notificatie nog 8 kansen
                notifyIcon1.BalloonTipText = "1 kans minder, je hebt nog 8 kansen";
                notifyIcon1.Icon = SystemIcons.Exclamation;
                notifyIcon1.ShowBalloonTip(1000);
                e.Graphics.DrawLine(new Pen(Color.Black, 2), 148, 190, 148, 50);
            }
        }

3 个答案:

答案 0 :(得分:0)

重绘控件(在您的情况下为Form1)时,将引发Paint事件(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.paint?view=netframework-4.7.2)。在很多情况下会发生这种情况,例如调整窗口大小,在窗体上绘图等。请尝试将通知逻辑移至当用户输入其游戏字母时运行的事件。我们需要查看您更多的项目,以获得更具体的答案。

答案 1 :(得分:0)

这是一个非常简单的示例,说明如何仅触发一次通知: 我已经迷上了LostFocus,但是您可以迷上了TextChanged

using System;
using System.Windows.Forms;
using WindowsFormsApp2.Properties;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox1.LostFocus += OnLostFocus;
            textBox2.LostFocus += OnLostFocus;
            textBox3.LostFocus += OnLostFocus;

            notifyIcon1.Icon = Resources.Icon1;
        }

        private void OnLostFocus(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox == null)
                throw new ArgumentNullException(nameof(textBox));

            // check for condition

            if (int.TryParse(textBox.Text, out var result))
                return;

            // show error

            notifyIcon1.BalloonTipText = "Error!";
            notifyIcon1.ShowBalloonTip(5000);
        }
    }
}

请注意,以这种方式报告错误确实是糟糕的UX,您应该考虑使用除NotifyIcon之外的其他机制:)

答案 2 :(得分:0)

因为if条件为>=,所以您不会收到多个通知

例如,当status8时:

  • status >= 1为真,notifyIcon1.ShowBalloonTip(1000)将运行
  • status >= 2也将为true,并且另一个ShowwBallonTip将运行
  • 依次类推

因此,您可能需要重新排序和重构if语句,第一个将是if,随后的语句将是else if

例如

if (status >= 3)
{
  // code
}
else if (status >= 2)
{
 // code
}
else if (status >= 1)
{
// and so on
}

看起来您实际上不需要>=比较,而实际上需要==