You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm中Timer事件触发时MessageBox弹窗数量递增问题求助

问题根源

弹窗数量逐次翻倍的核心原因是**Timer2_Tick事件被重复绑定**,大概率是你在Form2_Load()方法中重复执行了timer2.Tick += Timer2_Tick;这类绑定代码。每次调用Form2_Load()(比如点击No时),就会给Timer多绑定一次事件处理方法,导致后续每次Timer触发时,都会执行多次弹窗逻辑。

另外原代码中Timer的启停逻辑混乱,也会加剧事件触发的异常堆积。

解决方案

1. 统一Timer事件绑定时机

把Timer的事件绑定移到Form的构造函数中,确保只绑定一次:

public Form2()
{
    InitializeComponent();
    // 仅在这里绑定一次Tick事件
    timer2.Tick += Timer2_Tick;
    // 初始化时启动Timer
    timer2.Start();
}

2. 修正Timer_Tick逻辑

调整Timer的启停时机,避免事件堆积,同时简化逻辑分支:

private void Timer2_Tick(object sender, EventArgs e)
{
    bool found = false;
    // 先暂停Timer,避免处理过程中再次触发Tick
    timer2.Stop();

    // 检查ListBox2是否存在匹配项
    for (int i = 0; i < listBox2.Items.Count; i++)
    {
        string item = listBox2.Items[i].ToString();
        if (item == Globals.vivaboard)
        {
            found = true;
            break;
        }
    }

    if (found)
    {
        DialogResult result = MessageBox.Show("Press YES to enable", $"iTAC Disabled {Globals.vivaboard}", MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes)
        {
            auto_change();
        }
        // Yes/No分支都需要清空并重新加载,合并重复代码
        listBox2.Items.Clear();
        listBox1.Items.Clear();
        Form2_Load(null, EventArgs.Empty);
    }

    OTPM_Viva();
    // 处理完成后重启Timer,恢复周期性检查
    timer2.Start();
}

3. 清理Form2_Load()中的重复代码

修改Form2_Load(),移除其中重复绑定Timer事件或重复启动Timer的代码,仅保留数据加载逻辑:

private void Form2_Load(object sender, EventArgs e)
{
    // 这里只保留你的数据加载逻辑,比如从TXT读取数据填充ListBox等
    // ...

    // 如果必须在这里启动Timer,先停止再启动,避免重复触发
    if (timer2.Enabled)
        timer2.Stop();
    timer2.Start();
}

内容的提问来源于stack exchange,提问作者Katonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 16:05:39