在设计自定义控件时,经常需要在构造函数或者Load事件中添加初始化代码,但是这些代码在进入窗体设计也会被执行,造成了设计窗口出现异常的情况。
使用下面的代码,可以让你判断出是否处于窗体设计模式,进而保证代码只会在最终用户使用时才会被执行。
01 | public static bool IsDesignMode() |
02 | { |
03 | bool returnFlag = false ; |
04 |
05 | #if DEBUG |
06 | if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) |
07 | { |
08 | returnFlag = true ; |
09 | } |
10 | else if (Process.GetCurrentProcess().ProcessName == "devenv" ) |
11 | { |
12 | returnFlag = true ; |
13 | } |
14 | #endif |
15 |
16 | return returnFlag; |
17 | } |