-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNativeShellContextMenu.cs
More file actions
692 lines (581 loc) · 21.8 KB
/
Copy pathNativeShellContextMenu.cs
File metadata and controls
692 lines (581 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace c2flux
{
public sealed class NativeShellContextMenuCommand
{
public NativeShellContextMenuCommand(string text, Action execute)
{
Text = text ?? string.Empty;
Execute = execute ?? throw new ArgumentNullException(nameof(execute));
}
public string Text { get; }
public Action Execute { get; }
}
public static class NativeShellContextMenu
{
private const uint CustomCommandIdFirst = 1;
private const uint ShellCommandIdFirst = 1000;
private const uint ShellCommandIdLast = 0x7FFF;
private const uint MF_STRING = 0x0000;
private const uint MF_BYPOSITION = 0x0400;
private const uint MF_SEPARATOR = 0x0800;
private const uint TPM_RIGHTBUTTON = 0x0002;
private const uint TPM_RETURNCMD = 0x0100;
private const uint CMF_NORMAL = 0x00000000;
private const uint CMIC_MASK_UNICODE = 0x00004000;
private const uint CMIC_MASK_PTINVOKE = 0x20000000;
private const int SW_SHOWNORMAL = 1;
private const int WM_NULL = 0x0000;
private const int WM_INITMENUPOPUP = 0x0117;
private const int WM_MENUCHAR = 0x0120;
private const int WM_DRAWITEM = 0x002B;
private const int WM_MEASUREITEM = 0x002C;
private static readonly Guid IID_IShellFolder =
new Guid("000214E6-0000-0000-C000-000000000046");
private static readonly Guid IID_IContextMenu =
new Guid("000214E4-0000-0000-C000-000000000046");
public static bool Show(
IWin32Window owner,
string path,
Point screenLocation,
IReadOnlyList<NativeShellContextMenuCommand> customCommands,
AppLayout layout)
{
if (owner == null ||
string.IsNullOrWhiteSpace(path) ||
customCommands == null)
{
return false;
}
IntPtr absolutePidl = IntPtr.Zero;
IntPtr parentFolderPointer = IntPtr.Zero;
IntPtr contextMenuPointer = IntPtr.Zero;
IntPtr menuHandle = IntPtr.Zero;
IShellFolder parentFolder = null;
IContextMenu contextMenu = null;
try
{
int parseResult = SHParseDisplayName(
path,
IntPtr.Zero,
out absolutePidl,
0,
out _);
if (parseResult != 0 || absolutePidl == IntPtr.Zero)
return false;
Guid shellFolderGuid = IID_IShellFolder;
int bindResult = SHBindToParent(
absolutePidl,
ref shellFolderGuid,
out parentFolderPointer,
out IntPtr childPidl);
if (bindResult != 0 ||
parentFolderPointer == IntPtr.Zero ||
childPidl == IntPtr.Zero)
{
return false;
}
parentFolder = (IShellFolder)Marshal.GetObjectForIUnknown(
parentFolderPointer);
Guid contextMenuGuid = IID_IContextMenu;
IntPtr[] childPidls = { childPidl };
int contextResult = parentFolder.GetUIObjectOf(
owner.Handle,
1,
childPidls,
ref contextMenuGuid,
IntPtr.Zero,
out contextMenuPointer);
if (contextResult != 0 || contextMenuPointer == IntPtr.Zero)
return false;
contextMenu = (IContextMenu)Marshal.GetObjectForIUnknown(
contextMenuPointer);
menuHandle = CreatePopupMenu();
if (menuHandle == IntPtr.Zero)
return false;
int menuPosition = 0;
for (int index = 0; index < customCommands.Count; index++)
{
InsertMenu(
menuHandle,
(uint)menuPosition,
MF_BYPOSITION | MF_STRING,
new UIntPtr(CustomCommandIdFirst + (uint)index),
EscapeMenuText(customCommands[index].Text));
menuPosition++;
}
if (customCommands.Count > 0)
{
InsertMenu(
menuHandle,
(uint)menuPosition,
MF_BYPOSITION | MF_SEPARATOR,
UIntPtr.Zero,
null);
menuPosition++;
}
int queryResult = contextMenu.QueryContextMenu(
menuHandle,
(uint)menuPosition,
ShellCommandIdFirst,
ShellCommandIdLast,
CMF_NORMAL);
if (queryResult < 0)
return false;
NativeMenuTheme.Apply(layout);
IContextMenu3 contextMenu3 = contextMenu as IContextMenu3;
IContextMenu2 contextMenu2 = contextMenu as IContextMenu2;
using ShellMenuMessageWindow messageWindow =
new ShellMenuMessageWindow(
owner.Handle,
contextMenu2,
contextMenu3);
SetForegroundWindow(owner.Handle);
uint selectedCommand = TrackPopupMenuEx(
menuHandle,
TPM_RIGHTBUTTON | TPM_RETURNCMD,
screenLocation.X,
screenLocation.Y,
owner.Handle,
IntPtr.Zero);
PostMessage(owner.Handle, WM_NULL, IntPtr.Zero, IntPtr.Zero);
if (selectedCommand == 0)
return true;
uint customCommandIdLast =
CustomCommandIdFirst +
(uint)customCommands.Count -
1;
if (selectedCommand >= CustomCommandIdFirst &&
selectedCommand <= customCommandIdLast)
{
int customCommandIndex =
(int)(selectedCommand - CustomCommandIdFirst);
customCommands[customCommandIndex].Execute();
return true;
}
if (selectedCommand < ShellCommandIdFirst)
return true;
InvokeShellCommand(
contextMenu,
owner.Handle,
selectedCommand - ShellCommandIdFirst,
screenLocation);
return true;
}
catch
{
return false;
}
finally
{
if (menuHandle != IntPtr.Zero)
{
DestroyMenu(menuHandle);
}
ReleaseComObject(contextMenu);
ReleaseComObject(parentFolder);
if (contextMenuPointer != IntPtr.Zero)
{
Marshal.Release(contextMenuPointer);
}
if (parentFolderPointer != IntPtr.Zero)
{
Marshal.Release(parentFolderPointer);
}
if (absolutePidl != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(absolutePidl);
}
}
}
private static void InvokeShellCommand(
IContextMenu contextMenu,
IntPtr ownerHandle,
uint commandOffset,
Point screenLocation)
{
CMINVOKECOMMANDINFOEX commandInfo =
new CMINVOKECOMMANDINFOEX
{
cbSize = Marshal.SizeOf<CMINVOKECOMMANDINFOEX>(),
fMask = CMIC_MASK_UNICODE | CMIC_MASK_PTINVOKE,
hwnd = ownerHandle,
lpVerb = new IntPtr(commandOffset),
lpVerbW = new IntPtr(commandOffset),
nShow = SW_SHOWNORMAL,
ptInvoke = new POINT
{
X = screenLocation.X,
Y = screenLocation.Y
}
};
contextMenu.InvokeCommand(ref commandInfo);
}
private static string EscapeMenuText(string text)
{
return (text ?? string.Empty).Replace("&", "&&");
}
private static void ReleaseComObject(object comObject)
{
if (comObject == null || !Marshal.IsComObject(comObject))
return;
Marshal.FinalReleaseComObject(comObject);
}
private sealed class ShellMenuMessageWindow : NativeWindow, IDisposable
{
private readonly IContextMenu2 _contextMenu2;
private readonly IContextMenu3 _contextMenu3;
public ShellMenuMessageWindow(
IntPtr ownerHandle,
IContextMenu2 contextMenu2,
IContextMenu3 contextMenu3)
{
_contextMenu2 = contextMenu2;
_contextMenu3 = contextMenu3;
AssignHandle(ownerHandle);
}
public void Dispose()
{
ReleaseHandle();
}
protected override void WndProc(ref Message message)
{
if (message.Msg == WM_INITMENUPOPUP ||
message.Msg == WM_DRAWITEM ||
message.Msg == WM_MEASUREITEM ||
message.Msg == WM_MENUCHAR)
{
if (_contextMenu3 != null)
{
int result = _contextMenu3.HandleMenuMsg2(
(uint)message.Msg,
message.WParam,
message.LParam,
out IntPtr returnValue);
if (result == 0)
{
message.Result = returnValue;
return;
}
}
else if (_contextMenu2 != null)
{
int result = _contextMenu2.HandleMenuMsg(
(uint)message.Msg,
message.WParam,
message.LParam);
if (result == 0)
{
message.Result = IntPtr.Zero;
return;
}
}
}
base.WndProc(ref message);
}
}
private static class NativeMenuTheme
{
private const int SetPreferredAppModeOrdinal = 135;
private const int FlushMenuThemesOrdinal = 136;
private delegate int SetPreferredAppModeDelegate(
PreferredAppMode preferredAppMode);
private delegate void FlushMenuThemesDelegate();
private enum PreferredAppMode
{
Default = 0,
AllowDark = 1,
ForceDark = 2,
ForceLight = 3
}
public static void Apply(AppLayout layout)
{
if (Environment.OSVersion.Version.Major < 10)
return;
IntPtr moduleHandle = LoadLibrary("uxtheme.dll");
if (moduleHandle == IntPtr.Zero)
return;
try
{
IntPtr setPreferredAppModePointer = GetProcAddress(
moduleHandle,
new IntPtr(SetPreferredAppModeOrdinal));
IntPtr flushMenuThemesPointer = GetProcAddress(
moduleHandle,
new IntPtr(FlushMenuThemesOrdinal));
if (setPreferredAppModePointer == IntPtr.Zero ||
flushMenuThemesPointer == IntPtr.Zero)
{
return;
}
SetPreferredAppModeDelegate setPreferredAppMode =
Marshal.GetDelegateForFunctionPointer<SetPreferredAppModeDelegate>(
setPreferredAppModePointer);
FlushMenuThemesDelegate flushMenuThemes =
Marshal.GetDelegateForFunctionPointer<FlushMenuThemesDelegate>(
flushMenuThemesPointer);
PreferredAppMode preferredAppMode =
layout == AppLayout.WindowsDarkMode
? PreferredAppMode.ForceDark
: layout == AppLayout.WindowsLightMode
? PreferredAppMode.ForceLight
: PreferredAppMode.AllowDark;
setPreferredAppMode(preferredAppMode);
flushMenuThemes();
}
catch
{
}
finally
{
FreeLibrary(moduleHandle);
}
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214E6-0000-0000-C000-000000000046")]
private interface IShellFolder
{
[PreserveSig]
int ParseDisplayName(
IntPtr hwnd,
IntPtr bindContext,
[MarshalAs(UnmanagedType.LPWStr)] string displayName,
ref uint eaten,
out IntPtr itemIdList,
ref uint attributes);
[PreserveSig]
int EnumObjects(
IntPtr hwnd,
int flags,
out IntPtr enumIdList);
[PreserveSig]
int BindToObject(
IntPtr itemIdList,
IntPtr bindContext,
ref Guid interfaceId,
out IntPtr result);
[PreserveSig]
int BindToStorage(
IntPtr itemIdList,
IntPtr bindContext,
ref Guid interfaceId,
out IntPtr result);
[PreserveSig]
int CompareIDs(
IntPtr lParam,
IntPtr firstItemIdList,
IntPtr secondItemIdList);
[PreserveSig]
int CreateViewObject(
IntPtr hwndOwner,
ref Guid interfaceId,
out IntPtr result);
[PreserveSig]
int GetAttributesOf(
uint itemCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
IntPtr[] itemIdLists,
ref uint attributes);
[PreserveSig]
int GetUIObjectOf(
IntPtr hwndOwner,
uint itemCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
IntPtr[] itemIdLists,
ref Guid interfaceId,
IntPtr reserved,
out IntPtr result);
[PreserveSig]
int GetDisplayNameOf(
IntPtr itemIdList,
uint flags,
out STRRET name);
[PreserveSig]
int SetNameOf(
IntPtr hwnd,
IntPtr itemIdList,
[MarshalAs(UnmanagedType.LPWStr)] string name,
uint flags,
out IntPtr renamedItemIdList);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214E4-0000-0000-C000-000000000046")]
private interface IContextMenu
{
[PreserveSig]
int QueryContextMenu(
IntPtr menuHandle,
uint indexMenu,
uint commandIdFirst,
uint commandIdLast,
uint flags);
[PreserveSig]
int InvokeCommand(ref CMINVOKECOMMANDINFOEX commandInfo);
[PreserveSig]
int GetCommandString(
UIntPtr commandId,
uint flags,
IntPtr reserved,
IntPtr name,
uint maximumCharacters);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214F4-0000-0000-C000-000000000046")]
private interface IContextMenu2 : IContextMenu
{
[PreserveSig]
new int QueryContextMenu(
IntPtr menuHandle,
uint indexMenu,
uint commandIdFirst,
uint commandIdLast,
uint flags);
[PreserveSig]
new int InvokeCommand(ref CMINVOKECOMMANDINFOEX commandInfo);
[PreserveSig]
new int GetCommandString(
UIntPtr commandId,
uint flags,
IntPtr reserved,
IntPtr name,
uint maximumCharacters);
[PreserveSig]
int HandleMenuMsg(
uint message,
IntPtr wParam,
IntPtr lParam);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BCFCE0A0-EC17-11D0-8D10-00A0C90F2719")]
private interface IContextMenu3 : IContextMenu2
{
[PreserveSig]
new int QueryContextMenu(
IntPtr menuHandle,
uint indexMenu,
uint commandIdFirst,
uint commandIdLast,
uint flags);
[PreserveSig]
new int InvokeCommand(ref CMINVOKECOMMANDINFOEX commandInfo);
[PreserveSig]
new int GetCommandString(
UIntPtr commandId,
uint flags,
IntPtr reserved,
IntPtr name,
uint maximumCharacters);
[PreserveSig]
new int HandleMenuMsg(
uint message,
IntPtr wParam,
IntPtr lParam);
[PreserveSig]
int HandleMenuMsg2(
uint message,
IntPtr wParam,
IntPtr lParam,
out IntPtr result);
}
[StructLayout(LayoutKind.Sequential)]
private struct CMINVOKECOMMANDINFOEX
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
public IntPtr lpVerb;
public IntPtr lpParameters;
public IntPtr lpDirectory;
public int nShow;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr lpTitle;
public IntPtr lpVerbW;
public IntPtr lpParametersW;
public IntPtr lpDirectoryW;
public IntPtr lpTitleW;
public POINT ptInvoke;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Explicit, Size = 520)]
private struct STRRET
{
[FieldOffset(0)]
public uint Type;
[FieldOffset(4)]
public IntPtr Pointer;
[FieldOffset(4)]
public uint Offset;
[FieldOffset(4)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)]
public byte[] CharacterBuffer;
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int SHParseDisplayName(
string name,
IntPtr bindContext,
out IntPtr itemIdList,
uint attributesIn,
out uint attributesOut);
[DllImport("shell32.dll")]
private static extern int SHBindToParent(
IntPtr itemIdList,
ref Guid interfaceId,
out IntPtr parentFolder,
out IntPtr childItemIdList);
[DllImport("user32.dll")]
private static extern IntPtr CreatePopupMenu();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DestroyMenu(IntPtr menuHandle);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InsertMenu(
IntPtr menuHandle,
uint position,
uint flags,
UIntPtr newItemId,
string newItem);
[DllImport("user32.dll")]
private static extern uint TrackPopupMenuEx(
IntPtr menuHandle,
uint flags,
int x,
int y,
IntPtr ownerHandle,
IntPtr parameters);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr windowHandle);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PostMessage(
IntPtr windowHandle,
int message,
IntPtr wParam,
IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr LoadLibrary(string fileName);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr moduleHandle);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
private static extern IntPtr GetProcAddress(
IntPtr moduleHandle,
IntPtr procedureName);
}
}