【问题标题】:Why does this Visual Studio timer component work in design time?为什么这个 Visual Studio 计时器组件在设计时工作?
【发布时间】:2014-06-11 17:49:32
【问题描述】:

在 .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 硬件锁。令人惊讶的是,如果我取出锁,代码会在 design time(在 VS 2010 IDE 中)显示此弹出消息。

有人知道是什么原因吗?

【问题讨论】:

  • 停止调试后是否显示?
  • 应用程序未调试或未运行时。

标签: c# .net visual-studio ide


【解决方案1】:

这很正常,您的代码也可以在设计时运行。此方法的上下文尚不清楚,但是当您继承存在此方法的 Form 类时,您很有可能会让计时器计时。或者当您在 UserControl 中有此代码并将其放在表单上时。

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

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

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

【讨论】:

  • 是的,此方法在继承自 Form 类的类中。其他类也继承自它。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    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 了解更多背景信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多