如何防止Form_activated事件循环

本文关键字:事件 循环 activated 何防止 Form | 更新日期: 2023-09-27 18:20:18

我希望激活的事件只运行一次。我尝试过使用If条件,但Reload变量没有设置为false,因此它一直在无休止地循环。有办法绕过这个吗?

Form1.cs代码:

private void Form1_Activated(object sender, EventArgs e)
    {
        if (Class1.Reload == true) {
            Class1.Reload = false;
        }
    }

Class1.cs代码:

 public class Class1 {
    public static void Refresh() { Reload = true; }
    public static bool Reload { get; set; }

如何防止Form_activated事件循环

只需在第一次触发事件时取消订阅即可。

private void Form1_Activated(object sender, EventArgs e)
{
    this.Activated -= Form1_Activated;
    // Do other stuff here. 
}

虽然CathalMF的解决方案是有效的,但我将发布我实现的解决方案,其目的是在返回主窗体时刷新DatagridView

 private void Form1_Activated(object sender, EventArgs e) {
        if (Class1.Reload == true) {
            Activated -= Form1_Activated;
            Class1.Reload = false;
            //Here I implement the code to refresh a DatagridView
            Activated += Form1_Activated;
        }
    }

Class1.cs保持不变。