Search code examples
c#autocadautocad-plugin

C# AutoCAD | How to properly set the Icon on MenuItem in ContextMenuExtension


I'm trying to set an Icon for a MenuItem in a ContextMenu Extension, but the icon is set with defects: enter image description here

Original icon (16x16):
enter image description here

Code to set Icon:

polyline_item1.Icon = ACADConstructionPit.Properties.Resources.exchangeProfile;

How to properly set the Icon on MenuItem in ContextMenuExtension?


Solution

  • Example

    Code for getting an image from a file using the template path (%appdata%/Autodesk/ApplicationPlugins/POW_UPS.bundle/UI/_Images/):

    /// <summary>
        /// Get Icon for AutoCAD ContextMenuExtension: MenuItem.Icon 
        /// </summary>
        /// <param name="inIconFileName"></param>
        /// <returns></returns>
        public static System.Drawing.Icon GetIconForAppFromPathFile(string inIconFileName, string inFolderPath = null)
        {
            System.Drawing.Icon _ImageSourceForApp = null;
            try
            {
                if (string.IsNullOrEmpty(inIconFileName)) { return _ImageSourceForApp; }
    
                if (inFolderPath == null)
                {
                    // path to image folder: %appdata%/Autodesk/ApplicationPlugins/POW_EPS.bundle/UI/_Images/
                    var _PathToFolderIcons = $"{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Autodesk", "ApplicationPlugins", "POW_EPS.bundle", "UI", "_Images")}";
                    if (string.IsNullOrEmpty(_PathToFolderIcons)) { return _ImageSourceForApp; }
                    inFolderPath = _PathToFolderIcons;
                }
    
                IEnumerable<string> _AllPathIcons = Directory.GetFiles(inFolderPath, "*.png");
                string _PathIconFile = _AllPathIcons.FirstOrDefault(i => i.Contains(inIconFileName));
                Bitmap _BitmapFromFile = new Bitmap(_PathIconFile);
                Bitmap _ResizedBitmap = new Bitmap(_BitmapFromFile, new Size(16, 16));
                _ImageSourceForApp = Icon.FromHandle(_ResizedBitmap.GetHicon());
    
            }
            catch { }
            return _ImageSourceForApp;
        }
    

    Example of icon installation:

    menu_item.Icon = GetIconForAppFromPathFile("exchangeProfile.png");
    

    But, unfortunately, not all icons can be installed correctly: Bad

    Original image (32x32):
    Original image (32x32)