Skip to content

Code Quality: Replaced Vanara with CsWin32 in ContextMenu class #17136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Files.App.CsWin32/Extras.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,25 @@ public static unsafe nint SetWindowLongPtr(HWND hWnd, WINDOW_LONG_PTR_INDEX nInd
public const int PixelFormat32bppARGB = 2498570;
}

namespace Foundation
{
public partial struct PCSTR
{
public static unsafe PCSTR FromString(string value)
{
fixed (byte* p = global::System.Text.Encoding.UTF8.GetBytes(value))
{
return new PCSTR(p);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have no idea what you doing. Once getting out of fixed, the p won't be guaranteed to be fixed any longer.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do I then construct the struct from a string/int value?

Copy link
Member

@0x5bfa 0x5bfa May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have to pin the address until the method you want to call is returned.

fixed (char* pName = name)
{
    // PInvoke.Method(..., pName, ...);
}

So, this case you can't create a helper like that.

}
}

public static unsafe PCSTR FromInt(int value)
{
return new PCSTR((byte*)&value);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here too, taking pointer of an int value? For what.

}
}
}

namespace Extras
{
[GeneratedComInterface, Guid("EACDD04C-117E-4E17-88F4-D1B12B0E3D89"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
Expand Down
5 changes: 5 additions & 0 deletions src/Files.App.CsWin32/NativeMethods.txt
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,8 @@
GetKeyboardState
MapVirtualKey
GetKeyboardLayout
MENUITEMINFO

Check warning on line 228 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, arm64)

Method, type or constant "MENUITEMINFO" not found. Did you mean , "IMEMENUITEMINFOA", "IMEMENUITEMINFOW" or "MENUITEMINFOA" or "MENUITEMINFOW"?

Check warning on line 228 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Release, x64)

Method, type or constant "MENUITEMINFO" not found. Did you mean , "IMEMENUITEMINFOA", "IMEMENUITEMINFOW" or "MENUITEMINFOA" or "MENUITEMINFOW"?

Check warning on line 228 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, arm64)

Method, type or constant "MENUITEMINFO" not found. Did you mean , "IMEMENUITEMINFOA", "IMEMENUITEMINFOW" or "MENUITEMINFOA" or "MENUITEMINFOW"?

Check warning on line 228 in src/Files.App.CsWin32/NativeMethods.txt

View workflow job for this annotation

GitHub Actions / build (Debug, x64)

Method, type or constant "MENUITEMINFO" not found. Did you mean , "IMEMENUITEMINFOA", "IMEMENUITEMINFOW" or "MENUITEMINFOA" or "MENUITEMINFOW"?
GetMenuItemCount
GetMenuItemInfo
IContextMenu2
CreateMenu
Original file line number Diff line number Diff line change
@@ -1 +1 @@
cb1ca000ef2f03f1afc7bde9ed4fb2987669c89a58b63919e67574696091f60f
04fb6dcd84d19b858484bd1812b2361d06897f802eabaf430ec8799e1b3ca1f9
31 changes: 31 additions & 0 deletions src/Files.App/Helpers/Win32/Win32Helper.Storage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,37 @@ public static Task<bool> MountVhdDisk(string vhdPath)
}
}

public static Bitmap? GetBitmapFromHBitmap(Windows.Win32.Graphics.Gdi.HBITMAP hBitmap)
{
try
{
Bitmap bmp = Image.FromHbitmap((IntPtr)hBitmap);
if (Image.GetPixelFormatSize(bmp.PixelFormat) < 32)
return bmp;

Rectangle bmBounds = new Rectangle(0, 0, bmp.Width, bmp.Height);
var bmpData = bmp.LockBits(bmBounds, ImageLockMode.ReadOnly, bmp.PixelFormat);

if (IsAlphaBitmap(bmpData))
{
var alpha = GetAlphaBitmapFromBitmapData(bmpData);

bmp.UnlockBits(bmpData);
bmp.Dispose();

return alpha;
}

bmp.UnlockBits(bmpData);

return bmp;
}
catch
{
return null;
}
}

public static Shell32.ITaskbarList4? CreateTaskbarObject()
{
try
Expand Down
68 changes: 34 additions & 34 deletions src/Files.App/Utils/Shell/ContextMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

using System.Drawing;
using System.Runtime.InteropServices;
using Vanara.InteropServices;
using Vanara.PInvoke;
using Vanara.Windows.Shell;
using Windows.Win32;
using Windows.Win32.UI.WindowsAndMessaging;
using Windows.Win32.UI.Shell;
using Windows.Win32.Foundation;
using Windows.Win32.Graphics.Gdi;

namespace Files.App.Utils.Shell
{
Expand All @@ -16,9 +16,9 @@
/// </summary>
public partial class ContextMenu : Win32ContextMenu, IDisposable
{
private Shell32.IContextMenu _cMenu;
private IContextMenu _cMenu;

private User32.SafeHMENU _hMenu;
private HMENU _hMenu;

private readonly ThreadWithMessageQueue _owningThread;

Expand All @@ -31,7 +31,7 @@

public List<string> ItemsPath { get; }

private ContextMenu(Shell32.IContextMenu cMenu, User32.SafeHMENU hMenu, IEnumerable<string> itemsPath, ThreadWithMessageQueue owningThread, Func<string, bool>? itemFilter)
private ContextMenu(IContextMenu cMenu, HMENU hMenu, IEnumerable<string> itemsPath, ThreadWithMessageQueue owningThread, Func<string, bool>? itemFilter)
{
_cMenu = cMenu;
_hMenu = hMenu;
Expand Down Expand Up @@ -64,10 +64,10 @@
{
var currentWindows = Win32Helper.GetDesktopWindows();

var pici = new Shell32.CMINVOKECOMMANDINFOEX
var pici = new CMINVOKECOMMANDINFO
{
lpVerb = new SafeResourceId(verb, CharSet.Ansi),
nShow = ShowWindowCommand.SW_SHOWNORMAL,
lpVerb = PCSTR.FromString(verb),
nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL
};

pici.cbSize = (uint)Marshal.SizeOf(pici);
Expand All @@ -93,15 +93,15 @@
try
{
var currentWindows = Win32Helper.GetDesktopWindows();
var pici = new Shell32.CMINVOKECOMMANDINFOEX
var pici = new CMINVOKECOMMANDINFO
{
lpVerb = Macros.MAKEINTRESOURCE(itemID),
nShow = ShowWindowCommand.SW_SHOWNORMAL,
lpVerb = PCSTR.FromInt(itemID),
nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL,
};

pici.cbSize = (uint)Marshal.SizeOf(pici);
if (workingDirectory is not null)
pici.lpDirectoryW = workingDirectory;
pici.lpDirectory = PCSTR.FromString(workingDirectory);

await _owningThread.PostMethod(() => _cMenu.InvokeCommand(pici));
Win32Helper.BringToForeground(currentWindows);
Expand Down Expand Up @@ -161,9 +161,9 @@
// NOTE: The items are all in the same folder
using var sf = shellItems[0].Parent;

Shell32.IContextMenu menu = sf.GetChildrenUIObjects<Shell32.IContextMenu>(default, shellItems);
var hMenu = User32.CreatePopupMenu();
menu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, (Shell32.CMF)flags);
IContextMenu menu = sf.GetChildrenUIObjects<IContextMenu>(default, shellItems);
var hMenu = PInvoke.CreatePopupMenu();
menu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, flags);
var contextMenu = new ContextMenu(menu, hMenu, shellItems.Select(x => x.ParsingName), owningThread, itemFilter);
contextMenu.EnumMenuItems(hMenu, contextMenu.Items);

Expand All @@ -181,34 +181,34 @@
using var cMenu = await GetContextMenuForFiles(new string[] { $@"{Constants.UserEnvironmentPaths.SystemDrivePath}\" }, PInvoke.CMF_NORMAL);
}

private void EnumMenuItems(Vanara.PInvoke.HMENU hMenu, List<Win32ContextMenuItem> menuItemsResult, bool loadSubenus = false)
private void EnumMenuItems(HMENU hMenu, List<Win32ContextMenuItem> menuItemsResult, bool loadSubenus = false)
{
var itemCount = User32.GetMenuItemCount(hMenu);
var itemCount = PInvoke.GetMenuItemCount(hMenu);

var menuItemInfo = new User32.MENUITEMINFO()
var menuItemInfo = new MENUITEMINFOW()
{
fMask =
User32.MenuItemInfoMask.MIIM_BITMAP |
User32.MenuItemInfoMask.MIIM_FTYPE |
User32.MenuItemInfoMask.MIIM_STRING |
User32.MenuItemInfoMask.MIIM_ID |
User32.MenuItemInfoMask.MIIM_SUBMENU,
MENU_ITEM_MASK.MIIM_BITMAP |
MENU_ITEM_MASK.MIIM_FTYPE |
MENU_ITEM_MASK.MIIM_STRING |
MENU_ITEM_MASK.MIIM_ID |
MENU_ITEM_MASK.MIIM_SUBMENU,
};

menuItemInfo.cbSize = (uint)Marshal.SizeOf(menuItemInfo);

for (uint index = 0; index < itemCount; index++)
{
var menuItem = new ContextMenuItem();
var container = new SafeCoTaskMemString(512);
var cMenu2 = _cMenu as Shell32.IContextMenu2;
var container = new Marshal.SafeCoTaskMemString(512);
var cMenu2 = _cMenu as IContextMenu2;

menuItemInfo.dwTypeData = (IntPtr)container;

// See also, https://devblogs.microsoft.com/oldnewthing/20040928-00/?p=37723
menuItemInfo.cch = (uint)container.Capacity - 1;

var result = User32.GetMenuItemInfo(hMenu, index, true, ref menuItemInfo);
var result = PInvoke.GetMenuItemInfo(new , index, true, ref menuItemInfo);

Check failure on line 211 in src/Files.App/Utils/Shell/ContextMenu.cs

View workflow job for this annotation

GitHub Actions / build (Release, arm64)

A new expression requires an argument list or (),

Check failure on line 211 in src/Files.App/Utils/Shell/ContextMenu.cs

View workflow job for this annotation

GitHub Actions / build (Release, x64)

A new expression requires an argument list or (),

Check failure on line 211 in src/Files.App/Utils/Shell/ContextMenu.cs

View workflow job for this annotation

GitHub Actions / build (Debug, arm64)

A new expression requires an argument list or (),

Check failure on line 211 in src/Files.App/Utils/Shell/ContextMenu.cs

View workflow job for this annotation

GitHub Actions / build (Debug, x64)

A new expression requires an argument list or (),
if (!result)
{
container.Dispose();
Expand All @@ -234,7 +234,7 @@
continue;
}

if (menuItemInfo.hbmpItem != HBITMAP.NULL && !Enum.IsDefined(typeof(HBITMAP_HMENU), ((IntPtr)menuItemInfo.hbmpItem).ToInt64()))
if (menuItemInfo.hbmpItem != HBITMAP.Null && !Enum.IsDefined(typeof(HBITMAP_HMENU), ((IntPtr)menuItemInfo.hbmpItem).ToInt64()))
{
using var bitmap = Win32Helper.GetBitmapFromHBitmap(menuItemInfo.hbmpItem);

Expand All @@ -248,7 +248,7 @@
}
}

if (menuItemInfo.hSubMenu != Vanara.PInvoke.HMENU.NULL)
if (menuItemInfo.hSubMenu != HMENU.Null)
{
Debug.WriteLine("Item {0}: has submenu", index);
var subItems = new List<Win32ContextMenuItem>();
Expand All @@ -267,7 +267,7 @@
{
try
{
cMenu2?.HandleMenuMsg((uint)User32.WindowMessage.WM_INITMENUPOPUP, (IntPtr)hSubMenu, new IntPtr(index));
cMenu2?.HandleMenuMsg(PInvoke.WM_INITMENUPOPUP, (IntPtr)hSubMenu, new IntPtr(index));
}
catch (Exception ex) when (ex is InvalidCastException or ArgumentException)
{
Expand Down Expand Up @@ -316,7 +316,7 @@
}
}

private static string? GetCommandString(Shell32.IContextMenu cMenu, uint offset, Shell32.GCS flags = Shell32.GCS.GCS_VERBW)
private static string? GetCommandString(IContextMenu cMenu, uint offset, GCS flags = GCS.GCS_VERBW)
{
// A workaround to avoid an AccessViolationException on some items,
// notably the "Run with graphic processor" menu item of NVIDIA cards
Expand All @@ -325,11 +325,11 @@
return null;
}

SafeCoTaskMemString? commandString = null;
PSTR? commandString = null;

try
{
commandString = new SafeCoTaskMemString(512);
commandString = new PSTR(512);
cMenu.GetCommandString(new IntPtr(offset), flags, IntPtr.Zero, commandString, (uint)commandString.Capacity - 1);
Debug.WriteLine("Verb {0}: {1}", offset, commandString);

Expand Down Expand Up @@ -374,7 +374,7 @@
// TODO: Free unmanaged resources (unmanaged objects) and override a finalizer below
if (_hMenu is not null)
{
User32.DestroyMenu(_hMenu);
PInvoke.DestroyMenu(_hMenu);
_hMenu = null;
}
if (_cMenu is not null)
Expand Down
Loading