为什么这个Visual Studio计时器组件在设计时工作?

时间:2014-06-11 08:20:20

标签: c# .net visual-studio ide

在.Net windows表单应用程序中,有一个启用了表单的计时器。以下代码是句柄:

    private void timer2_Tick(object sender, EventArgs e)
    {
        try
        {
            if ( !CheckLock())
            {
                MessageBox.Show("No lock found.");
                this.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("No lock found.");
            this.Close();
        }
    }

锁是usb硬件锁。令人惊讶的是,如果我取出锁定,代码会在设计时间(在VS 2010 IDE中)显示此弹出消息。

有谁知道原因是什么?

3 个答案:

答案 0 :(得分:3)

这很正常,您的代码也可以在设计时运行。此方法的上下文不清楚,但是当您(例如,继承此方法所在的Form类)时,您将获得计时器的好几率。或者当您在UserControl中使用此代码并将其放在表单上时。

这是设计师提供WYSIWYG外观的主要方式。就像设置控件的BackgroundImage属性一样,它也会立即显示设计器中的图像。换句话说,BackgroundImage属性setter和控件的OnPaintBackground()方法都在设计时执行。基本规则是基类中的任何代码都可以在设计时运行。您添加到派生类的代码不会。

修复它很简单,使用DesignTime属性来防止计时器在设计时处于活动状态。像这样:

    timer2.Enabled = !this.DesignTime;    // Instead of true

答案 1 :(得分:3)

您可以在不想在设计模式下运行的代码中使用以下条件:

if (!this.DesignMode)
{
// Code here only executes when running, not in design mode
}

答案 2 :(得分:1)

这是因为计时器也在设计时运行。 您应该测试代码是否在DesignMode中运行:

private void timer2_Tick(object sender, EventArgs e)
{
    if( this.DesignMode ) return; 

    try
    {
        if ( !CheckLock())
        {
            MessageBox.Show("No lock found.");
            this.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("No lock found.");
        this.Close();
    }
}

授予Controls, properties, events and timers running in design timeBuilding Windows Forms Controls and Components with Rich Design-Time Features获取更多背景信息。