Monday, March 28, 2011

Writing Windows Shell Extension with .NET Framework 4 (C#, VB.NET) - Part 4: Context Menu Handler with Menu-item Bitmaps

In "Writing Windows Shell Extension with .NET Framework 4 (C#, VB.NET) - Part 1: Context Menu Handler", we introduced how to write Windows shell context menu handler using .NET 4:

7065.part1.png

Lots of developers have this follow-up question: how can I add bitmap icons to those context menu items?

Here you are the directly working code samples from Microsoft All-In-One Code Framework!
Sample download: C#, VB.NET

5635.thumbnail.png

Implementation Details

The menu items in the context menu were added in the implementation of IContextMenu.QueryContextMenu:

        public int QueryContextMenu(
            IntPtr hMenu,
            uint iMenu,
            uint idCmdFirst,
            uint idCmdLast,
            uint uFlags)
        {
            ......
            // Use either InsertMenu or InsertMenuItem to add menu items.
            MENUITEMINFO mii = new MENUITEMINFO();
            mii.cbSize = (uint)Marshal.SizeOf(mii);
            mii.fMask = MIIM.MIIM_STRING | MIIM.MIIM_FTYPE | MIIM.MIIM_ID | MIIM.MIIM_STATE;
            mii.wID = idCmdFirst + IDM_DISPLAY;
            mii.fType = MFT.MFT_STRING;
            mii.dwTypeData = this.menuText;
            mii.fState = MFS.MFS_ENABLED;
            if (!NativeMethods.InsertMenuItem(hMenu, iMenu, true, ref mii))
            {
                return Marshal.GetHRForLastWin32Error();
            }
            ......