/// <summary>Invokes the specified verb on the shell item(s).</summary> public void InvokeVerb(string verb) { var invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = (uint)Marshal.SizeOf(invoke); invoke.lpVerb = new SafeResourceId(verb); ComInterface.InvokeCommand(invoke); }
private void InvokeCommand(int index) { var invoke = new CMINVOKECOMMANDINFOEX(index) { nShow = ShowWindowCommand.SW_SHOWNORMAL }; m_ComInterface2.InvokeCommand(invoke); }
/// <summary>Invokes the specified verb on the shell item(s).</summary> /// <param name="verb">The verb to invoke.</param> /// <param name="show">Flags that specify how to display any opened window.</param> public void InvokeVerb(string verb, ShowWindowCommand show = ShowWindowCommand.SW_NORMAL) { var invoke = new CMINVOKECOMMANDINFOEX { cbSize = (uint)Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX)), lpVerb = new SafeResourceId(verb, CharSet.Ansi), nShow = show }; ComInterface.InvokeCommand(invoke); }
void InvokeCommand(IntPtr command, Point pt, IntPtr ansiCommand) { const int SW_SHOWNORMAL = 1; var invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.nShow = SW_SHOWNORMAL; invoke.fMask = CMIC.FlagNoUi | CMIC.Unicode; invoke.lpVerb = ansiCommand; invoke.lpVerbW = command; //invoke.ptInvoke = pt; m_ComInterface.InvokeCommand(ref invoke); }
/// <summary>Invokes the command.</summary> /// <param name="verb"> /// The address of a null-terminated string that specifies the language-independent name of the command to carry out. This member is /// typically a string when a command is being activated by an application. The system provides predefined constant values for the /// following command strings. /// <para> /// If a canonical verb exists and a menu handler does not implement the canonical verb, it must return a failure code to enable the /// next handler to be able to handle this verb.Failing to do this will break functionality in the system including ShellExecute. /// </para> /// <para> /// Alternatively, rather than a pointer, this parameter can be MAKEINTRESOURCE(offset) where offset is the menu-identifier offset /// of the command to carry out. Implementations can use the IS_INTRESOURCE macro to detect that this alternative is being employed. /// The Shell uses this alternative when the user chooses a menu command. /// </para> /// </param> /// <param name="show">A set of values to pass to the ShowWindow function if the command displays a window or starts an application.</param> /// <param name="parent"> /// A handle to the window that is the owner of the shortcut menu. An extension can also use this handle as the owner of any message /// boxes or dialog boxes it displays. Callers must specify a legitimate HWND that can be used as the owner window for any UI that /// may be displayed. Failing to specify an HWND when calling from a UI thread (one with windows already created) will result in /// reentrancy and possible bugs in the implementation of this call. /// </param> /// <param name="location">If supplied, the point where the command is invoked.</param> /// <param name="allowAsync"> /// The implementation can spin off a new thread or process to handle the call and does not need to block on completion of the /// function being invoked. For example, if the verb is "delete" the call may return before all of the items have been deleted. /// Since this is advisory, calling applications that specify this flag cannot guarantee that this request will be honored if they /// are not familiar with the implementation of the verb that they are invoking. /// </param> /// <param name="shiftDown"> /// If <see langword="true"/>, the SHIFT key is pressed. Use this instead of polling the current state of the keyboard that may have /// changed since the verb was invoked. /// </param> /// <param name="ctrlDown"> /// If <see langword="true"/>, the CTRL key is pressed. Use this instead of polling the current state of the keyboard that may have /// changed since the verb was invoked.. /// </param> /// <param name="hotkey">An optional keyboard shortcut to assign to any application activated by the command.</param> /// <param name="logUsage"> /// If <see langword="true"/>, indicates that the method might want to keep track of the item being invoked for features like the /// "Recent documents" menu. /// </param> /// <param name="noZoneChecks"> /// Do not perform a zone check. This flag allows ShellExecuteEx to bypass zone checking put into place by IAttachmentExecute. /// </param> public void InvokeCommand(ResourceId verb, ShowWindowCommand show = ShowWindowCommand.SW_SHOWNORMAL, HWND parent = default, Point?location = default, bool allowAsync = false, bool shiftDown = false, bool ctrlDown = false, uint hotkey = 0, bool logUsage = false, bool noZoneChecks = false) { var invoke = new CMINVOKECOMMANDINFOEX { cbSize = (uint)Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX)), hwnd = parent, fMask = (parent.IsNull ? CMIC.CMIC_MASK_FLAG_NO_UI : 0) | (hotkey != 0 ? CMIC.CMIC_MASK_HOTKEY : 0), lpVerb = verb, nShow = show, dwHotKey = hotkey, }; if (allowAsync) { invoke.fMask |= CMIC.CMIC_MASK_ASYNCOK; } if (shiftDown) { invoke.fMask |= CMIC.CMIC_MASK_SHIFT_DOWN; } if (ctrlDown) { invoke.fMask |= CMIC.CMIC_MASK_CONTROL_DOWN; } if (logUsage) { invoke.fMask |= CMIC.CMIC_MASK_FLAG_LOG_USAGE; } if (noZoneChecks) { invoke.fMask |= CMIC.CMIC_MASK_NOZONECHECKS; } if (location.HasValue) { invoke.ptInvoke = location.Value; invoke.fMask |= CMIC.CMIC_MASK_PTINVOKE; } if (!verb.IsIntResource) { invoke.lpVerbW = (string)verb; invoke.fMask |= CMIC.CMIC_MASK_UNICODE; } ComInterface.InvokeCommand(invoke); }
private void InvokeCommand(IContextMenu oContextMenu, uint nCmd, string strFolder, bool ctrl, bool shift, int x, int y) { CMINVOKECOMMANDINFOEX invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = s_InvokeCommand; invoke.lpVerb = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectory = strFolder; invoke.lpVerbW = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectoryW = strFolder; invoke.fMask = CMIC.UNICODE | CMIC.PTINVOKE | (ctrl ? CMIC.CONTROL_DOWN : 0) | (shift ? CMIC.SHIFT_DOWN : 0); invoke.ptInvoke = new POINT(x, y); invoke.nShow = SW.SHOWNORMAL; oContextMenu.InvokeCommand(ref invoke); }
private void InvokeCommand(IContextMenu oContextMenu, uint nCmd, string strFolder, Point pointInvoke) { var invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = cbInvokeCommand; invoke.lpVerb = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectory = strFolder; invoke.lpVerbW = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectoryW = strFolder; invoke.fMask = CMIC.UNICODE | CMIC.PTINVOKE | ((Control.ModifierKeys & Keys.Control) != 0 ? CMIC.CONTROL_DOWN : 0) | ((Control.ModifierKeys & Keys.Shift) != 0 ? CMIC.SHIFT_DOWN : 0); invoke.ptInvoke = new POINT(pointInvoke.X, pointInvoke.Y); invoke.nShow = SW.SHOWNORMAL; oContextMenu.InvokeCommand(ref invoke); }
/// <summary> /// Invokes a specific command from an IContextMenu /// </summary> /// <param name="iContextMenu">the IContextMenu containing the item</param> /// <param name="workingDir">the parent directory from where to invoke</param> /// <param name="cmd">the index of the command to invoke</param> /// <param name="ptInvoke">the point (in screen coordinates) from which to invoke</param> protected void InvokeCommand(IContextMenu iContextMenu, string workingDir, uint cmd, Point ptInvoke) { CMINVOKECOMMANDINFOEX invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = Interop.cbInvokeCommand; invoke.lpVerb = (IntPtr)cmd; invoke.lpVerbW = (IntPtr)cmd; invoke.lpDirectory = workingDir; invoke.lpDirectoryW = workingDir; invoke.fMask = CMIC.ASYNCOK | CMIC.FLAG_LOG_USAGE | CMIC.UNICODE | CMIC.PTINVOKE | ((Control.ModifierKeys & Keys.Control) != 0 ? CMIC.CONTROL_DOWN : 0) | ((Control.ModifierKeys & Keys.Shift) != 0 ? CMIC.SHIFT_DOWN : 0); invoke.ptInvoke = new NativeMethods.POINT(ptInvoke.X, ptInvoke.Y); invoke.nShow = NativeMethods.WindowShowStyle.ShowNormal; iContextMenu.InvokeCommand(ref invoke); }
private static void InvokeCommand(IContextMenu contextMenu, uint nCmd, string strFolder, Point pointInvoke) { CMINVOKECOMMANDINFOEX invoke = new CMINVOKECOMMANDINFOEX { cbSize = cbInvokeCommand, lpVerb = (IntPtr)(nCmd - CMD_FIRST), lpDirectory = strFolder, lpVerbW = (IntPtr)(nCmd - CMD_FIRST), lpDirectoryW = strFolder, fMask = CMIC.UNICODE | CMIC.PTINVOKE | ((Control.ModifierKeys & Keys.Control) != 0 ? CMIC.CONTROL_DOWN : 0) | ((Control.ModifierKeys & Keys.Shift) != 0 ? CMIC.SHIFT_DOWN : 0), ptInvoke = new POINT(pointInvoke.X, pointInvoke.Y), nShow = SW.SHOWNORMAL }; _ = contextMenu.InvokeCommand(ref invoke); }
/// <summary> /// Saves the invoke command information. /// </summary> /// <param name="isUnicode">if set to <c>true</c> the unicode structure is used.</param> /// <param name="ici">The ici.</param> /// <param name="iciex">The iciex.</param> private void SaveInvokeCommandInfo(bool isUnicode, CMINVOKECOMMANDINFO ici, CMINVOKECOMMANDINFOEX iciex) { if (isUnicode) { // Create command info from the Unicode structure. currentInvokeCommandInfo = new InvokeCommandInfo { WindowHandle = iciex.hwnd, ShowCommand = iciex.nShow }; } else { // Create command info from the ANSI structure. currentInvokeCommandInfo = new InvokeCommandInfo { WindowHandle = ici.hwnd, ShowCommand = ici.nShow }; } }
public void QueryTest([Values] CMF cmf) { using var pshi = ComReleaserFactory.Create(SHCreateItemFromParsingName <IShellItem>(TestCaseSources.WordDoc)); using var pcm = ComReleaserFactory.Create(pshi.Item.BindToHandler <IContextMenu>(null, BHID.BHID_SFUIObject.Guid())); using var hmenu = CreatePopupMenu(); Assert.That(pcm.Item.QueryContextMenu(hmenu, 0, 1, int.MaxValue, cmf), ResultIs.Successful); var miis = MenuItemInfo.GetMenuItems(hmenu); using var memstr = new SafeCoTaskMemString(1024, CharSet.Ansi); for (int i = 0; i < miis.Length; i++) { ShowMII(miis[i], i); } if (cmf == CMF.CMF_NORMAL) { var oid = miis.First(m => m.Verb == "properties").Id; var cix = new CMINVOKECOMMANDINFOEX((int)oid - 1); pcm.Item.InvokeCommand(cix); } void ShowMII(MenuItemInfo mii, int c, int indent = 0) { mii.Verb = mii.Type == MenuItemType.MFT_STRING && pcm.Item.GetCommandString((IntPtr)(int)(mii.Id - 1), GCS.GCS_VERBA, default, memstr, memstr.Size) == HRESULT.S_OK ? memstr.ToString() : "";
private void InvokeCommand(IContextMenu oContextMenu, uint nCmd, string strFolder, Point pointInvoke) { CMINVOKECOMMANDINFOEX invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = cbInvokeCommand; invoke.lpVerb = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectory = strFolder; invoke.lpVerbW = (IntPtr)(nCmd - CMD_FIRST); invoke.lpDirectoryW = strFolder; invoke.fMask = CMIC.UNICODE | CMIC.PTINVOKE | ((Control.ModifierKeys & Keys.Control) != 0 ? CMIC.CONTROL_DOWN : 0) | ((Control.ModifierKeys & Keys.Shift) != 0 ? CMIC.SHIFT_DOWN : 0); invoke.ptInvoke = new POINT(pointInvoke.X, pointInvoke.Y); invoke.nShow = SW.SHOWNORMAL; oContextMenu.InvokeCommand(ref invoke); }
/// <summary> /// Called to invoke the comamand. /// </summary> /// <param name="pici">The command info pointer.</param> int IContextMenu.InvokeCommand(IntPtr pici) { // We'll work out whether the commandis unicode or not... var isUnicode = false; // We could have been provided with a CMINVOKECOMMANDINFO or a // CMINVOKECOMMANDINFOEX - cast to the small and then check the size. var ici = (CMINVOKECOMMANDINFO)Marshal.PtrToStructure(pici, typeof(CMINVOKECOMMANDINFO)); var iciex = new CMINVOKECOMMANDINFOEX(); // Is it a CMINVOKECOMMANDINFOEX? if (ici.cbSize == Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX))) { // Check the unicode flag, get the extended command info. if ((ici.fMask & CMIC.CMIC_MASK_UNICODE) != 0) { isUnicode = true; iciex = (CMINVOKECOMMANDINFOEX)Marshal.PtrToStructure(pici, typeof(CMINVOKECOMMANDINFOEX)); } } // The derived class MAY need some of the extended command data, // so we store it now. It can be retrieved and used in the handler // of the menu item. SaveInvokeCommandInfo(isUnicode, ici, iciex); // If we're not unicode and the verb hiword is not zero, // we've got an ANSI verb string. if (!isUnicode && User32.HighWord(ici.verb.ToInt32()) != 0) { // Get the verb. var verb = Marshal.PtrToStringAnsi(ici.verb); // DebugLog this key event. Log(string.Format("Invoke ANSI verb {0}", verb)); // Try and invoke the command. If we don't invoke it, throw // E_FAIL so that other handlers can try. if (!nativeContextMenuWrapper.TryInvokeCommand(verb)) { Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } // If we're unicode, and the verb hiword is not zero, // we've got a unicode command string. else if (isUnicode && User32.HighWord(iciex.verbW.ToInt32()) != 0) { // Get the verb. var verb = Marshal.PtrToStringAnsi(ici.verb); // DebugLog this key event. Log(string.Format("Invoke Unicode verb {0}", verb)); // Try and invoke the command. If we don't invoke it, throw // E_FAIL so that other handlers can try. if (!nativeContextMenuWrapper.TryInvokeCommand(verb)) { Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } // The verb pointer isn't a string at all, it's an index. else { // Get the command index. Logically, we don't actually need to // loword it, as the hiword is zero, but we're following the // documentation rigourously. var index = User32.LowWord(ici.verb.ToInt32()); // DebugLog this key event. Log(string.Format("Invoke command index {0}", index)); // Try and invoke the command. If we don't invoke it, throw // E_FAIL so that other handlers can try. if (!nativeContextMenuWrapper.TryInvokeCommand(index)) { Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } // Return success. return(WinError.S_OK); }
private static void HandleApplicationLaunch(string application, AppServiceRequestReceivedEventArgs args) { var arguments = args.Request.Message.Get("Arguments", ""); var workingDirectory = args.Request.Message.Get("WorkingDirectory", ""); try { Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = application; // Show window if workingDirectory (opening terminal) process.StartInfo.CreateNoWindow = string.IsNullOrEmpty(workingDirectory); if (arguments == "runas") { process.StartInfo.UseShellExecute = true; process.StartInfo.Verb = "runas"; if (Path.GetExtension(application).ToLower() == ".msi") { process.StartInfo.FileName = "msiexec.exe"; process.StartInfo.Arguments = $"/a \"{application}\""; } } else if (arguments == "runasuser") { process.StartInfo.UseShellExecute = true; process.StartInfo.Verb = "runasuser"; if (Path.GetExtension(application).ToLower() == ".msi") { process.StartInfo.FileName = "msiexec.exe"; process.StartInfo.Arguments = $"/i \"{application}\""; } } else { process.StartInfo.Arguments = arguments; } process.StartInfo.WorkingDirectory = workingDirectory; process.Start(); } catch (Win32Exception) { Process process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.Verb = "runas"; process.StartInfo.FileName = application; process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = workingDirectory; try { process.Start(); } catch (Win32Exception) { try { var split = application.Split(';').Where(x => !string.IsNullOrWhiteSpace(x)); if (split.Count() == 1) { Process.Start(application); } else { var groups = split.GroupBy(x => new { Dir = Path.GetDirectoryName(x), Prog = Win32API.GetFileAssociation(x).Result ?? Path.GetExtension(x) }); foreach (var group in groups) { if (!group.Any()) { continue; } var files = group.Select(x => new ShellItem(x)); using var sf = files.First().Parent; IContextMenu menu = null; try { menu = sf.GetChildrenUIObjects <IContextMenu>(null, files.ToArray()); menu.QueryContextMenu(Vanara.PInvoke.HMENU.NULL, 0, 0, 0, CMF.CMF_DEFAULTONLY); var pici = new CMINVOKECOMMANDINFOEX(); pici.lpVerb = CMDSTR_OPEN; pici.nShow = Vanara.PInvoke.ShowWindowCommand.SW_SHOW; pici.cbSize = (uint)Marshal.SizeOf(pici); menu.InvokeCommand(pici); } finally { foreach (var elem in files) { elem.Dispose(); } if (menu != null) { Marshal.ReleaseComObject(menu); } } } } } catch (Win32Exception) { // Cannot open file (e.g DLL) } catch (ArgumentException) { // Cannot open file (e.g DLL) } } } }
public void ShowContextMenu(Point pos, CMF aditionalFlags, bool IsOnEmpty = false) { using (ContextMenu mnu = new ContextMenu()) { this.Populate(mnu, aditionalFlags); this._Timer.Interval = 2; this._Timer.Tick += TimerOnTick; this._Timer.Stop(); var view = new ContextMenu(); var sortMenu = new ContextMenu(); var groupMenu = new ContextMenu(); var count = User32.GetMenuItemCount(mnu.Handle); var itemInfo = new MENUITEMINFO(); itemInfo.fMask = MIIM.MIIM_FTYPE | MIIM.MIIM_DATA | MIIM.MIIM_STRING | MIIM.MIIM_SUBMENU | MIIM.MIIM_ID; if (User32.GetMenuItemInfo(mnu.Handle, count - 1, true, ref itemInfo)) { if ((itemInfo.fType & MFT.MFT_SEPARATOR) != 0) { User32.DeleteMenu(mnu.Handle, count - 1, MF.MF_BYPOSITION); } } User32.GetMenuItemInfo(mnu.Handle, User32.GetMenuItemCount(mnu.Handle) - 3, true, ref itemInfo); if (itemInfo.hSubMenu == IntPtr.Zero) { User32.GetMenuItemInfo(mnu.Handle, User32.GetMenuItemCount(mnu.Handle) - 1, true, ref itemInfo); } this._NewMenuPtr = itemInfo.hSubMenu; if (IsOnEmpty) { this.GenerateExplorerBackgroundMenuItems(view, mnu, sortMenu, groupMenu); } else { if (this._Items.FirstOrDefault()?.IsFolder == true) { this.GenerateMenuItem(mnu, System.Windows.Application.Current?.FindResource("mnuOpenNewTab")?.ToString(), 301, false, 1); } } this.RemoveDuplicatedSeparators(mnu); var command = User32.TrackPopupMenuEx(mnu.Handle, TPM.TPM_RETURNCMD, pos.X, pos.Y, m_MessageWindow.Handle, IntPtr.Zero); if (command > 0 && command < m_CmdFirst) { switch (command) { case 245: this._ShellView.SetGroupOrder(false); break; case 246: this._ShellView.SetGroupOrder(); break; case 247: var colasc = this._ShellView.Collumns.FirstOrDefault(w => w.ID == this._ShellView.LastSortedColumnId); this._ShellView.SetSortCollumn(true, colasc, SortOrder.Ascending); break; case 248: var coldesc = this._ShellView.Collumns.FirstOrDefault(w => w.ID == this._ShellView.LastSortedColumnId); this._ShellView.SetSortCollumn(true, coldesc, SortOrder.Descending); break; case 249: this._ShellView.PasteAvailableFiles(); break; case 250: this._ShellView.RefreshContents(); break; case 251: this._ShellView.View = ShellViewStyle.ExtraLargeIcon; break; case 252: this._ShellView.View = ShellViewStyle.LargeIcon; break; case 253: this._ShellView.View = ShellViewStyle.Medium; break; case 254: this._ShellView.View = ShellViewStyle.SmallIcon; break; case 255: this._ShellView.View = ShellViewStyle.List; break; case 256: this._ShellView.View = ShellViewStyle.Details; break; case 257: this._ShellView.View = ShellViewStyle.Tile; break; case 258: this._ShellView.View = ShellViewStyle.Content; break; case 259: this._ShellView.View = ShellViewStyle.Thumbstrip; break; case 260: if (this._ShellView.IsGroupsEnabled) { this._ShellView.DisableGroups(); } break; case 301: this._ShellView.RaiseMiddleClickOnItem(this._Items.First()); break; default: break; } if (command >= 262 && command <= 262 + this._ShellView.Collumns.Count) { this._ShellView.SetSortCollumn(true, this._ShellView.Collumns[command - 262], SortOrder.Ascending); } else if (command > 260 && command != 301) { if (!this._ShellView.IsGroupsEnabled) { this._ShellView.EnableGroups(); } this._ShellView.GenerateGroupsFromColumn(this._ShellView.Collumns[command - (262 + this._ShellView.Collumns.Count) - 1], false); } } if (command > m_CmdFirst) { var info = string.Empty; var bytes = new byte[256]; IntPtr pszName = Marshal.AllocHGlobal(256); this.m_ComInterface3.GetCommandString(command - (int)m_CmdFirst, 4, 0, pszName, 260); //var index = 0; //while (index < bytes.Length - 1 && (bytes[index] != 0 || bytes[index + 1] != 0)) { index += 2; } //if (index < bytes.Length - 1) { info = Encoding.Unicode.GetString(bytes, 0, index); } info = Marshal.PtrToStringAuto(pszName); switch (info) { case "open": //(control as ShellView)?.OpenOrNavigateItem(); break; case "rename": //(control as ShellView)?.RenameSelectedItem(); break; case "cut": //(control as ShellView)?.CutSelectedFiles(); break; case "copy": //(control as ShellView)?.CopySelectedFiles(); break; default: CMINVOKECOMMANDINFOEX cminvokecommandinfoex = new CMINVOKECOMMANDINFOEX { lpVerb = (IntPtr)(command - m_CmdFirst), lpVerbW = (IntPtr)(command - m_CmdFirst) }; cminvokecommandinfoex.cbSize = Marshal.SizeOf(cminvokecommandinfoex); //cminvokecommandinfoex.lpDirectory = this._ShellView.CurrentFolder.ParsingName; //cminvokecommandinfoex.lpDirectoryW = this._ShellView.CurrentFolder.ParsingName; cminvokecommandinfoex.fMask = ((CMIC.Asyncok | CMIC.PtInvoke | CMIC.Unicode | CMIC.FlagNoUi) | (((Control.ModifierKeys & Keys.Control) > Keys.None) ? CMIC.ControlDown : ((CMIC)0))) | (((Control.ModifierKeys & Keys.Shift) > Keys.None) ? CMIC.ShiftDown : ((CMIC)0)); cminvokecommandinfoex.ptInvoke = pos; cminvokecommandinfoex.nShow = 1; //cminvokecommandinfoex.hwnd = this._ShellView.LVHandle; this.m_ComInterface3.InvokeCommand(ref cminvokecommandinfoex); //this.InvokeCommand((IntPtr)(command - m_CmdFirst), pos, (IntPtr)(command - m_CmdFirst)); break; } } User32.DestroyMenu(mnu.Handle); view.Dispose(); User32.DestroyMenu(view.Handle); sortMenu.Dispose(); User32.DestroyMenu(sortMenu.Handle); groupMenu.Dispose(); User32.DestroyMenu(groupMenu.Handle); } Marshal.ReleaseComObject(this.m_ComInterface); Marshal.ReleaseComObject(this.m_ComInterface2); Marshal.ReleaseComObject(this.m_ComInterface3); Marshal.Release(this._Result); this._Result = IntPtr.Zero; }
void InvokeCommand(IntPtr command, Point pt, IntPtr ansiCommand) { const int SW_SHOWNORMAL = 1; var invoke = new CMINVOKECOMMANDINFOEX(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.nShow = SW_SHOWNORMAL; invoke.fMask = (int)(CMIC.FlagNoUi | CMIC.Unicode); invoke.lpVerb = ansiCommand; invoke.lpVerbW = command; //invoke.ptInvoke = pt; m_ComInterface.InvokeCommand(ref invoke); }
/// <summary> /// Carry out the command associated with a shortcut menu item. /// </summary> /// <param name="pici"> /// A pointer to a CMINVOKECOMMANDINFO or CMINVOKECOMMANDINFOEX structure /// containing information about the command. /// </param> public void InvokeCommand(IntPtr pici) { bool isUnicode = false; // Determine which structure is being passed in, CMINVOKECOMMANDINFO or // CMINVOKECOMMANDINFOEX based on the cbSize member of lpcmi. Although // the lpcmi parameter is declared in Shlobj.h as a CMINVOKECOMMANDINFO // structure, in practice it often points to a CMINVOKECOMMANDINFOEX // structure. This struct is an extended version of CMINVOKECOMMANDINFO // and has additional members that allow Unicode strings to be passed. CMINVOKECOMMANDINFO ici = (CMINVOKECOMMANDINFO)Marshal.PtrToStructure( pici, typeof(CMINVOKECOMMANDINFO)); CMINVOKECOMMANDINFOEX iciex = new CMINVOKECOMMANDINFOEX(); if (ici.cbSize == Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX))) { if ((ici.fMask & CMIC.CMIC_MASK_UNICODE) != 0) { isUnicode = true; iciex = (CMINVOKECOMMANDINFOEX)Marshal.PtrToStructure(pici, typeof(CMINVOKECOMMANDINFOEX)); } } // Determines whether the command is identified by its offset or verb. // There are two ways to identify commands: // // 1) The command's verb string // 2) The command's identifier offset // // If the high-order word of lpcmi->lpVerb (for the ANSI case) or // lpcmi->lpVerbW (for the Unicode case) is nonzero, lpVerb or lpVerbW // holds a verb string. If the high-order word is zero, the command // offset is in the low-order word of lpcmi->lpVerb. // For the ANSI case, if the high-order word is not zero, the command's // verb string is in lpcmi->lpVerb. if (!isUnicode && NativeMethods.HighWord(ici.verb.ToInt32()) != 0) { // Is the verb supported by this context menu extension? if (Marshal.PtrToStringAnsi(ici.verb) == verb) { OnVerbDisplayFileName(ici.hwnd); } else { // If the verb is not recognized by the context menu handler, it // must return E_FAIL to allow it to be passed on to the other // context menu handlers that might implement that verb. Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } // For the Unicode case, if the high-order word is not zero, the // command's verb string is in lpcmi->lpVerbW. else if (isUnicode && NativeMethods.HighWord(iciex.verbW.ToInt32()) != 0) { // Is the verb supported by this context menu extension? if (Marshal.PtrToStringUni(iciex.verbW) == verb) { OnVerbDisplayFileName(ici.hwnd); } else { // If the verb is not recognized by the context menu handler, it // must return E_FAIL to allow it to be passed on to the other // context menu handlers that might implement that verb. Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } // If the command cannot be identified through the verb string, then // check the identifier offset. else { // Is the command identifier offset supported by this context menu // extension? if (NativeMethods.LowWord(ici.verb.ToInt32()) == IDM_DISPLAY) { OnVerbDisplayFileName(ici.hwnd); } else { // If the verb is not recognized by the context menu handler, it // must return E_FAIL to allow it to be passed on to the other // context menu handlers that might implement that verb. Marshal.ThrowExceptionForHR(WinError.E_FAIL); } } }
public static void Main(string[] args) { IShellItem recyleBin; string str; IntPtr ptr = IntPtr.Zero; int res; //// From Windows 7 //res = ShellItemUtilities.SHGetKnownFolderItem(ShellItemUtilities.FOLDERID_RecycleBinFolder, 0, IntPtr.Zero, typeof(IShellItem).GUID, out recyleBin); //if (res < 0) //{ // Marshal.ThrowExceptionForHR(res); //} // Windows >= Vista equivalent var pidl = default(ShellItemUtilities.PIDLIST_ABSOLUTE); try { res = ShellItemUtilities.SHGetKnownFolderIDList(ShellItemUtilities.FOLDERID_RecycleBinFolder, 0, IntPtr.Zero, out pidl); if (res < 0) { Marshal.ThrowExceptionForHR(res); } res = ShellItemUtilities.SHCreateItemFromIDList(pidl, typeof(IShellItem).GUID, out recyleBin); if (res < 0) { Marshal.ThrowExceptionForHR(res); } } finally { ShellItemUtilities.ILFree2(pidl); } //// Example of use of GetDisplayName //try //{ // recyleBin.GetDisplayName(2, out ptr); // str = Marshal.PtrToStringUni(ptr); //} //finally //{ // if (ptr != IntPtr.Zero) // { // Marshal.FreeCoTaskMem(ptr); // ptr = IntPtr.Zero; // } //} var pids = new List <ShellItemUtilities.PIDLIST_ABSOLUTE>(); try { foreach (IShellItem si in recyleBin.Enumerate()) { try { si.GetDisplayName(0, out ptr); str = Marshal.PtrToStringUni(ptr); Console.WriteLine(str); // Remember to free the pid! res = ShellItemUtilities.SHGetIDListFromObject(si, out pidl); if (res < 0) { Marshal.ThrowExceptionForHR(res); } pids.Add(pidl); } finally { if (ptr != IntPtr.Zero) { Marshal.FreeCoTaskMem(ptr); ptr = IntPtr.Zero; } } } var pids2 = pids.ToArray(); IShellItemArray sia; res = ShellItemUtilities.SHCreateShellItemArrayFromIDLists(pids2.Length, pids2, out sia); if (res < 0) { Marshal.ThrowExceptionForHR(res); } object cmTemp; sia.BindToHandler(IntPtr.Zero, ShellItemUtilities.BHID_SFUIObject, typeof(IContextMenu).GUID, out cmTemp); var cm = (IContextMenu)cmTemp; // To see verbs //var verbsAnsi = ContextMenuUtilities.GetVerbs(cm, true); //var verbsUnicode = ContextMenuUtilities.GetVerbs(cm, false); var cmd = new CMINVOKECOMMANDINFOEX { cbSize = Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX)), fMask = 0x00000400 /* CMIC_MASK_FLAG_NO_UI */ , lpVerb = "delete", }; cm.InvokeCommand(ref cmd); } finally { foreach (var pid in pids) { ShellItemUtilities.ILFree2(pid); } } //// Single file example //foreach (var item in recyleBin.Enumerate().Take(5)) //{ // object cmTemp; // item.BindToHandler(IntPtr.Zero, ShellItemUtilities.BHID_SFUIObject, typeof(IContextMenu).GUID, out cmTemp); // var cm = (IContextMenu)cmTemp; ////// To see verbs //// var verbsAnsi = ContextMenuUtilities.GetVerbs(cm, true); //// var verbsUnicode = ContextMenuUtilities.GetVerbs(cm, false); // var cmd = new CMINVOKECOMMANDINFOEX // { // cbSize = Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX)), // fMask = 0x00000400 /* CMIC_MASK_FLAG_NO_UI */ // , // lpVerb = "delete", // }; // cm.InvokeCommand(ref cmd); //} }