Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 289345
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:53:55+00:00 2026-05-12T05:53:55+00:00

I have been considering using the code example shown at Shell Style Drag and

  • 0

I have been considering using the code example shown at Shell Style Drag and Drop in .NET – Part 3 within a WPF project. The sample project works fine, it is a great article so check it out!

However when moving the code to my project I receive an error when compiling “Unsafe code may only appear if compiling with /unsafe” I understand that I could just change the compile options, however I would prefer to not have the unsafe code in there. The unsafe code is as follows.

How can I make this code safe? I don’t really have experience in this field.

/// <summary>
/// Replaces any pixel with a zero alpha value with the specified transparency key.
/// </summary>
/// <param name="bmpData">The bitmap data in which to perform the operation.</param>
/// <param name="transKey">The transparency color. This color is rendered transparent
/// by the DragDropHelper.</param>
/// <remarks>
/// This function only supports 32-bit pixel formats for now.
/// </remarks>
private static void ReplaceTransparentPixelsWithTransparentKey(BitmapData bmpData, DrawingColor transKey)
{
    DrawingPixelFormat pxFormat = bmpData.PixelFormat;

    if (DrawingPixelFormat.Format32bppArgb == pxFormat
        || DrawingPixelFormat.Format32bppPArgb == pxFormat)
    {
        int transKeyArgb = transKey.ToArgb();

        // We will just iterate over the data... we don't care about pixel location,
        // just that every pixel is checked.
        unsafe
        {
            byte* pscan = (byte*)bmpData.Scan0.ToPointer();
            {
                for (int y = 0; y < bmpData.Height; ++y, pscan += bmpData.Stride)
                {
                    int* prgb = (int*)pscan;
                    for (int x = 0; x < bmpData.Width; ++x, ++prgb)
                    {
                        // If the alpha value is zero, replace this pixel's color
                        // with the transparency key.
                        if ((*prgb & 0xFF000000L) == 0L)
                            *prgb = transKeyArgb;
                    }
                }
            }
        }
    }
    else
    {
        // If it is anything else, we aren't supporting it, but we
        // won't throw, cause it isn't an error
        System.Diagnostics.Trace.TraceWarning("Not converting transparent colors to transparency key.");
        return;
    }
}

The function calling this code is as follows, maybe the ReplaceTransparentPixelsWithTransparentKey function could be removed entirely by another method. Any ideas?

/// <summary>
/// Gets a System.Drawing.Bitmap from a BitmapSource.
/// </summary>
/// <param name="source">The source image from which to create our Bitmap.</param>
/// <param name="transparencyKey">The transparency key. This is used by the DragDropHelper
/// in rendering transparent pixels.</param>
/// <returns>An instance of Bitmap which is a copy of the BitmapSource's image.</returns>
private static Bitmap GetBitmapFromBitmapSource(BitmapSource source, Color transparencyKey)
{
    // Copy at full size
    Int32Rect sourceRect = new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight);

    // Convert to our destination pixel format
    DrawingPixelFormat pxFormat = ConvertPixelFormat(source.Format);

    // Create the Bitmap, full size, full rez
    Bitmap bmp = new Bitmap(sourceRect.Width, sourceRect.Height, pxFormat);
    // If the format is an indexed format, copy the color palette
    if ((pxFormat & DrawingPixelFormat.Indexed) == DrawingPixelFormat.Indexed)
        ConvertColorPalette(bmp.Palette, source.Palette);

    // Get the transparency key as a System.Drawing.Color
    DrawingColor transKey = transparencyKey.ToDrawingColor();

    // Lock our Bitmap bits, we need to write to it
    BitmapData bmpData = bmp.LockBits(
        sourceRect.ToDrawingRectangle(),
        ImageLockMode.ReadWrite,
        pxFormat);
    {
        // Copy the source bitmap data to our new Bitmap
        source.CopyPixels(sourceRect, bmpData.Scan0, bmpData.Stride * sourceRect.Height, bmpData.Stride);

        // The drag image seems to work in full 32-bit color, except when
        // alpha equals zero. Then it renders those pixels at black. So
        // we make a pass and set all those pixels to the transparency key
        // color. This is only implemented for 32-bit pixel colors for now.
        if ((pxFormat & DrawingPixelFormat.Alpha) == DrawingPixelFormat.Alpha)
            ReplaceTransparentPixelsWithTransparentKey(bmpData, transKey);
    }
    // Done, unlock the bits
    bmp.UnlockBits(bmpData);

    return bmp;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T05:53:55+00:00Added an answer on May 12, 2026 at 5:53 am

    If you don’t want a significant performance hit, then you don’t really have any other options.

    You really shouldn’t be scared of unsafe keyword and the associated compiler switch, either – I often see people trying to find some workaround that is still unsafe (e.g. using Marshal, or Win32 API), but doesn’t require unsafe keyword. There’s no point in that – if anything, it’s more harmful, because unsafe stands out.

    In this case, for example, you could of course move the entire pointer arithmetic part into a C DLL or C++/CLI assembly, and invoke that from C# directly or via P/Invoke. But what would be the point?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 153k
  • Answers 153k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I believe you can create indexes on temporary tables as… May 12, 2026 at 10:17 am
  • Editorial Team
    Editorial Team added an answer My guess is that the compiler and linker does some… May 12, 2026 at 10:17 am
  • Editorial Team
    Editorial Team added an answer This basically describes a way to push work between threads;… May 12, 2026 at 10:17 am

Related Questions

What I mean by this, is that sometimes architects look to simplify and improve
I work on a somewhat large web application, and the backend is mostly in
I build and maintain a set of Flash components that is distributed to publishers
Now I'm working on a web project. I need to create a XML document
Does anyone have any good references for equations which can be implemented relatively easily

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.