C# - 阻止代码在设计器中执行

djd*_*d87 2 compact-framework image-manipulation image-processing c#-2.0

我正在执行一行无法在设计器中执行的代码,导致我的所有控件的公共属性不再显示在设计器中.因此,我无法再在Visual Studios Design View中看到任何使用该控件的表单.

有问题的代码行调用一个不安全的代码项目,它执行一些图像处理; 评论它使设计视图重现生机.但是,代码执行完美,所以我无法理解设计器中代码失败的原因.这是被调用的代码:

        /// <summary>
        /// Performs a color adjustment on the source bitmap. 
        /// </summary>
        /// <param name="source">The bitmap to be processed. This is changed by the
        /// process action.</param>
        /// <param name="redChange">change to the red value. Can be negative.</param>
        /// <param name="greenChange">change to the green value. Can be negative.</param>
        /// <param name="blueChange">change to the blue value. Can be negative.</param>
        /// <returns></returns>
        public static Bitmap ProcessColor(Bitmap source, int redChange, int greenChange, int blueChange)
        {
            sourceBitmap = source;

            // lock the source bitmap
            sourceBitmapData = getBitmapData(sourceBitmap, ref sourceWidth);
            sourcepBase = (Byte*)sourceBitmapData.Scan0.ToPointer();

            PixelData* pPixel;

            for (int y = 0; y < source.Height; y++)
            {
                pPixel = (PixelData*)(sourcepBase + y * sourceWidth);
                for (int x = 0; x < source.Width; x++)
                {
                    int redVal = pPixel->red + redChange;
                    if ( redVal <0 ) redVal = 0;
                    if ( redVal > 255) redVal = 255;
                    pPixel->red = (byte)redVal;

                    int greenVal = pPixel->green + greenChange;
                    if ( greenVal <0 ) greenVal = 0;
                    if ( greenVal > 255) greenVal = 255;
                    pPixel->green = (byte)greenVal;

                    int blueVal = pPixel->blue + blueChange;
                    if (blueVal < 0) blueVal = 0;
                    if (blueVal > 255) blueVal = 255;
                    pPixel->blue = (byte)blueVal;

                    pPixel++;
                }
            }

            sourceBitmap.UnlockBits(sourceBitmapData);
            sourceBitmapData = null;
            sourcepBase = null;

            return source;
        }
Run Code Online (Sandbox Code Playgroud)

(由OpenNETCF社区提供)

我的项目没有标记为不安全,但上面代码所在的项目标记为不安全.这两个项目都需要标记为不安全吗?

或者,有没有办法可以阻止设计器中触发的代码行(我在设计视图中实际上不需要输出此代码,因为它只是从提供的图像生成图像的禁用版本).

编辑:阻止代码运行不能解决问题.仅对该行进行注释可以使设计视图起作用.将行放入(即使放入if [false == true]语句中)会导致设计者显示错误,而不是表单.

Ant*_*lev 5

将部分代码包装在if:

if(!DesignMode)
{
    // Your "unsafe" code goes here
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Compact Framework,请使用以下命令:

if(Site != null && !Site.DesignMode)
{
    // Your "unsafe" code goes here
}
Run Code Online (Sandbox Code Playgroud)

有关野兽的实际情况,请参阅此帖子DesignMode.