/// <summary> /// Add commands to a shortcut menu. /// </summary> /// <param name="hMenu">A handle to the shortcut menu.</param> /// <param name="iMenu"> /// The zero-based position at which to insert the first new menu item. /// </param> /// <param name="idCmdFirst"> /// The minimum value that the handler can specify for a menu item ID. /// </param> /// <param name="idCmdLast"> /// The maximum value that the handler can specify for a menu item ID. /// </param> /// <param name="uFlags"> /// Optional flags that specify how the shortcut menu can be changed. /// </param> /// <returns> /// If successful, returns an HRESULT value that has its severity value set /// to SEVERITY_SUCCESS and its code value set to the offset of the largest /// command identifier that was assigned, plus one. /// </returns> public int QueryContextMenu( IntPtr hMenu, uint iMenu, uint idCmdFirst, uint idCmdLast, uint uFlags) { // If uFlags include CMF_DEFAULTONLY then we should not do anything. if (((uint)CMF.CMF_DEFAULTONLY & uFlags) != 0) { return WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, 0); } uint uID = idCmdFirst; IntPtr hSubmenu = NativeMethods.CreatePopupMenu(); // Use InsertMenuItem to add main menu items. MENUITEMINFO mii = new MENUITEMINFO(); mii.cbSize = (uint)Marshal.SizeOf(mii); mii.fMask = MIIM.MIIM_BITMAP | MIIM.MIIM_SUBMENU | MIIM.MIIM_FTYPE | MIIM.MIIM_ID | MIIM.MIIM_STATE | MIIM.MIIM_STRING; mii.wID = idCmdFirst + IDM_DISPLAY; mii.fType = MFT.MFT_STRING; mii.dwTypeData = this._menuText; mii.fState = MFS.MFS_ENABLED; mii.hbmpItem = this._menuBmp; mii.hSubMenu = hSubmenu; if (!NativeMethods.InsertMenuItem(hMenu, iMenu, true, ref mii)) { return Marshal.GetHRForLastWin32Error(); } // Get all loaded printers. _printerList = LoadAllPrinters(); for (int i = 0; i < _printerList.Count; ++i) { // Use InsertMenu to add submenu items. if (!NativeMethods.InsertMenu( hSubmenu, (uint)i, 0x00000400, uID++, _printerList[i]["Location"])) { return Marshal.GetHRForLastWin32Error(); } } // Return an HRESULT value with the severity set to SEVERITY_SUCCESS. // Set the code value to the offset of the largest command identifier // that was not assigned return WinError.MAKE_HRESULT(WinError.SEVERITY_SUCCESS, 0, uID - idCmdFirst); }
public static extern bool InsertMenuItem( IntPtr hMenu, uint uItem, [MarshalAs(UnmanagedType.Bool)] bool fByPosition, ref MENUITEMINFO mii);