计时器正在我的表单的另一个实例上触发事件

时间:2014-09-24 15:43:37

标签: c# timer callback

我有同一个对话框的多个实例。我传入一个枚举,以便对话框知道要显示的信息。我的表单中有定时器触发操作(在这种情况下,单击按钮单击示例)。但是,当这些计时器触发时,它们只会被一个(并且始终是最后创建的表单)而不是其他表单捕获。我希望触发计时器的表单能够捕获它。我错过了什么?

public partial class Form1 : Form
{
    public enum Animal { CAT, DOG, PIG };
    public Form1()
    {
        InitializeComponent();

        Form2 F21 = new Form2(Animal.CAT);
        F21.Show();

        Form2 F22 = new Form2(Animal.DOG);
        F22.Show();

        Form2 F23 = new Form2(Animal.PIG);
        F23.Show();
    }

public partial class Form2 : Form
{
    int buttonCount = 0;
    Form1.Animal Animal;
    private static System.Threading.Timer refreshListViewTimer;

    public Form2(Form1.Animal TheAnimal)
    {
        InitializeComponent();
        Animal = TheAnimal;
        Text = TheAnimal.ToString();
        refreshListViewTimer = new System.Threading.Timer(OnRefreshListTimer);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        refreshListViewTimer.Change(50, System.Threading.Timeout.Infinite);
    }

    private void OnRefreshListTimer(object sender)
    {
        if (!this.IsDisposed)
            Invoke(new RefreshListDelegate(this.RefreshList), new object[] { });
    }

    private delegate void RefreshListDelegate();
    private void RefreshList()
    {
        buttonCount++;
        Text = this.Animal.ToString() + " " + buttonCount.ToString();
    }
}

在这种情况下,无论我单击哪个表单,PIG对话框都会递增。

0 个答案:

没有答案