C# 判断是否是在设计模式下有效的方法

  public static bool IsDesignMode()  
    {  
      bool returnFlag = false;  
 
#if DEBUG  
      if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)  
      {  
        returnFlag = true;  
      }  
      else if (Process.GetCurrentProcess().ProcessName == "devenv")  
      {  
        returnFlag = true;  
      }  
#endif  
  
      return returnFlag;  
    }  

WinForm里每个Control对象都有 DesignMode 属性,可以判断是否是在设计时。 

  但 DesignMode 真的能判断当前是否是设计时吗??我们来做个小实验,先写一个测试控件: 

public class TestControl : System.Windows.Forms.UserControl 
   public TestControl() 
        System.Windows.Forms.MessageBox.Show( this.DesignMode.ToString() ); 
   } 
}


  然后我们把这个控件编译拖拽到另外一个 UserControl : TestContainerA 
  这个时候 TestControl.DesignMode  是 True 
  我们再把这个 TestContainerA 编译拖拽到一个新的用户控件或窗体里: TestContainerB 
  这个时候弹出来的 TestControl.DesignMode  却是 False !! 

  真是个神奇的现象。。也就是说一个控件只有在它自己被拖拽到设计器的时候,其 DesignMode 才是真,如果它被包含在其他控件中被加入  到设计器,那么那个控件才是在设计模式,而它不是!换句话说,DesignMode 并不能反映当前环境是否是运行时,它只能告诉你,这个控件当前是不是直接被设计器操作(嵌套的已经不算了) 
  花了一个多小时才跟踪发现这个错误...设计时控件的无法创建错误真是不好调试 

  Thanks to jonnyyu,这个解释比较容易理解和正确的: 
  winform的Design环境是由控件的容器维护的。当控件嵌套在一个没有design环境的容器空间中时其实就是运行时状态。 

posted on 2017-05-09 13:45  shaozhuyong  阅读(3933)  评论(0编辑  收藏  举报