Search code examples
c#winformsiconsico

How to make .ico format icon in task bar appear transparent?


I would like the background of the task bar icon that appears when my windows form application opens to be transparent. However, the icon has a white background when it appears in the task bar. I opened the .ico file and it has the checkered background that indicates transparency.

How do I make the background of the icon in the taskbar transparent?

This is the first time I have added an icon to a windows form application. I also tried with a .png file but what showed in the task bar was just the default .png icon.

Here is the code which declares object icon in the scope of the class:

Icon icon = Icon.ExtractAssociatedIcon("galaxyicon.ico");

I use the code below in each Form_Load method to set the icon as the icon object in the task bar.

this.Icon = icon; 

I expected a transparent icon in this case but got a white background instead.


Solution

  • You need to define the "transparent" color of the icon, like:

    //using System.Drawing;
    
    #region MakeTransparentIcon
    
        ///<summary>
        /// Manipulates the background of an Icon
        ///</summary>
        ///<param name="icon">Icon source</param>
        ///<param name="disposeIcon">Icon dispose</param>
        ///<returns><see cref="Icon"/> or <see cref="T:null"/></returns>
        public static Icon MakeTransparentIcon(Icon icon, bool disposeIcon = true)
        {
            if (icon != null)
            {
                using (Bitmap bm = icon.ToBitmap())
                {
                    bm.MakeTransparent(Color.Transparent); // define the background as transparent
                                                           // you need to align the color to your needs
                    if (disposeIcon)
                    {
                        icon.Dispose();
                    }
                    return Icon.FromHandle(bm.GetHicon());
                }
            }
            return null;
        }
        #endregion