-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShellContextMenu.cs
1596 lines (1443 loc) · 55 KB
/
ShellContextMenu.cs
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Plugin_Everything {
/// <summary>
/// "Stand-alone" shell context menu
///
/// Create an instance and call ShowContextMenu with a list of FileInfo for the files.
/// Limitation is that it only handles files in the same directory but it can be fixed
/// by changing the way files are translated into PIDLs.
///
/// Based on FileBrowser in C# from CodeProject
/// http://www.codeproject.com/useritems/FileBrowser.asp
///
/// Hooking class taken from MSDN Magazine Cutting Edge column
/// http://msdn.microsoft.com/msdnmag/issues/02/10/CuttingEdge/
///
/// Andreas Johansson
/// afjohansson@hotmail.com
/// http://afjohansson.spaces.live.com
/// </summary>
/// <example>
/// ShellContextMenu scm = new ShellContextMenu();<br />
/// FileInfo[] files = new FileInfo[1];<br />
/// files[0] = new FileInfo(@"c:\windows\notepad.exe");<br />
/// scm.ShowContextMenu(this.Handle, files, Cursor.Position);<br />
/// </example>
public class ShellContextMenu : NativeWindow { //disabled warnings for Quokka
#region Constructor
/// <summary>Default constructor</summary>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
public ShellContextMenu() {
this.CreateHandle(new CreateParams());
}
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
#endregion
#region Destructor
/// <summary>Ensure all resources get released</summary>
~ShellContextMenu() {
ReleaseAll();
}
#endregion
#region GetContextMenuInterfaces()
/// <summary>Gets the interfaces to the context menu</summary>
/// <param name="oParentFolder">Parent folder</param>
/// <param name="arrPIDLs">PIDLs</param>
/// <returns>true if it got the interfaces, otherwise false</returns>
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
private bool GetContextMenuInterfaces(IShellFolder oParentFolder, IntPtr[] arrPIDLs, out IntPtr ctxMenuPtr) {
int nResult = oParentFolder.GetUIObjectOf(
IntPtr.Zero,
(uint) arrPIDLs.Length,
arrPIDLs,
ref IID_IContextMenu,
IntPtr.Zero,
out ctxMenuPtr);
if (S_OK == nResult) {
_oContextMenu = (IContextMenu) Marshal.GetTypedObjectForIUnknown(ctxMenuPtr, typeof(IContextMenu));
return true;
} else {
ctxMenuPtr = IntPtr.Zero;
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oContextMenu = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
return false;
}
}
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
#endregion
#region Override
/// <summary>
/// This method receives WindowMessages. It will make the "Open With" and "Send To" work
/// by calling HandleMenuMsg and HandleMenuMsg2. It will also call the OnContextMenuMouseHover
/// method of Browser when hovering over a ContextMenu item.
/// </summary>
/// <param name="m">the Message of the Browser's WndProc</param>
/// <returns>true if the message has been handled, false otherwise</returns>
protected override void WndProc(ref Message m) {
#region IContextMenu
if (_oContextMenu != null &&
m.Msg == (int) WM.MENUSELECT &&
( (int) ShellHelper.HiWord(m.WParam) & (int) MFT.SEPARATOR ) == 0 &&
( (int) ShellHelper.HiWord(m.WParam) & (int) MFT.POPUP ) == 0) {
string info = string.Empty;
if (ShellHelper.LoWord(m.WParam) == (int) CMD_CUSTOM.ExpandCollapse)
info = "Expands or collapses the current selected item";
else {
info = "";
}
}
#endregion
#region IContextMenu2
if (_oContextMenu2 != null &&
( m.Msg == (int) WM.INITMENUPOPUP ||
m.Msg == (int) WM.MEASUREITEM ||
m.Msg == (int) WM.DRAWITEM )) {
if (_oContextMenu2.HandleMenuMsg(
(uint) m.Msg, m.WParam, m.LParam) == S_OK)
return;
}
#endregion
#region IContextMenu3
if (_oContextMenu3 != null &&
m.Msg == (int) WM.MENUCHAR) {
if (_oContextMenu3.HandleMenuMsg2(
(uint) m.Msg, m.WParam, m.LParam, IntPtr.Zero) == S_OK)
return;
}
#endregion
base.WndProc(ref m);
}
#endregion
#region InvokeCommand
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);
}
#endregion
#region ReleaseAll()
/// <summary>
/// Release all allocated interfaces, PIDLs
/// </summary>
private void ReleaseAll() {
if (null != _oContextMenu) {
Marshal.ReleaseComObject(_oContextMenu);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oContextMenu = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
if (null != _oContextMenu2) {
Marshal.ReleaseComObject(_oContextMenu2);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oContextMenu2 = null;
}
if (null != _oContextMenu3) {
Marshal.ReleaseComObject(_oContextMenu3);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oContextMenu3 = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
if (null != _oDesktopFolder) {
Marshal.ReleaseComObject(_oDesktopFolder);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oDesktopFolder = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
if (null != _oParentFolder) {
Marshal.ReleaseComObject(_oParentFolder);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_oParentFolder = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
if (null != _arrPIDLs) {
FreePIDLs(_arrPIDLs);
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_arrPIDLs = null;
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
}
#endregion
#region GetDesktopFolder()
/// <summary>
/// Gets the desktop folder
/// </summary>
/// <returns>IShellFolder for desktop folder</returns>
private IShellFolder GetDesktopFolder() {
IntPtr pUnkownDesktopFolder = IntPtr.Zero;
if (null == _oDesktopFolder) {
// Get desktop IShellFolder
int nResult = SHGetDesktopFolder(out pUnkownDesktopFolder);
if (S_OK != nResult) {
throw new ShellContextMenuException("Failed to get the desktop shell folder");
}
_oDesktopFolder = (IShellFolder) Marshal.GetTypedObjectForIUnknown(pUnkownDesktopFolder, typeof(IShellFolder));
}
return _oDesktopFolder;
}
#endregion
#region GetParentFolder()
/// <summary>
/// Gets the parent folder
/// </summary>
/// <param name="folderName">Folder path</param>
/// <returns>IShellFolder for the folder (relative from the desktop)</returns>
private IShellFolder GetParentFolder(string folderName) {
if (null == _oParentFolder) {
IShellFolder oDesktopFolder = GetDesktopFolder();
if (null == oDesktopFolder) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
// Get the PIDL for the folder file is in
IntPtr pPIDL = IntPtr.Zero;
uint pchEaten = 0;
SFGAO pdwAttributes = 0;
int nResult = oDesktopFolder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, folderName, ref pchEaten, out pPIDL, ref pdwAttributes);
if (S_OK != nResult) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
IntPtr pStrRet = Marshal.AllocCoTaskMem(MAX_PATH * 2 + 4);
Marshal.WriteInt32(pStrRet, 0, 0);
nResult = _oDesktopFolder.GetDisplayNameOf(pPIDL, SHGNO.FORPARSING, pStrRet);
StringBuilder strFolder = new StringBuilder(MAX_PATH);
StrRetToBuf(pStrRet, pPIDL, strFolder, MAX_PATH);
Marshal.FreeCoTaskMem(pStrRet);
pStrRet = IntPtr.Zero;
_strParentFolder = strFolder.ToString();
// Get the IShellFolder for folder
IntPtr pUnknownParentFolder = IntPtr.Zero;
nResult = oDesktopFolder.BindToObject(pPIDL, IntPtr.Zero, ref IID_IShellFolder, out pUnknownParentFolder);
// Free the PIDL first
Marshal.FreeCoTaskMem(pPIDL);
if (S_OK != nResult) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
_oParentFolder = (IShellFolder) Marshal.GetTypedObjectForIUnknown(pUnknownParentFolder, typeof(IShellFolder));
}
return _oParentFolder;
}
#endregion
#region GetPIDLs()
/// <summary>
/// Get the PIDLs
/// </summary>
/// <param name="arrFI">Array of FileInfo</param>
/// <returns>Array of PIDLs</returns>
protected IntPtr[] GetPIDLs(FileInfo[] arrFI) {
if (null == arrFI || 0 == arrFI.Length) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
IShellFolder oParentFolder = GetParentFolder(arrFI[0].DirectoryName);
if (null == oParentFolder) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
IntPtr[] arrPIDLs = new IntPtr[arrFI.Length];
int n = 0;
foreach (FileInfo fi in arrFI) {
// Get the file relative to folder
uint pchEaten = 0;
SFGAO pdwAttributes = 0;
IntPtr pPIDL = IntPtr.Zero;
int nResult = oParentFolder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, fi.Name, ref pchEaten, out pPIDL, ref pdwAttributes);
if (S_OK != nResult) {
FreePIDLs(arrPIDLs);
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
arrPIDLs[n] = pPIDL;
n++;
}
return arrPIDLs;
}
/// <summary>
/// Get the PIDLs
/// </summary>
/// <param name="arrFI">Array of DirectoryInfo</param>
/// <returns>Array of PIDLs</returns>
protected IntPtr[] GetPIDLs(DirectoryInfo[] arrFI) {
if (null == arrFI || 0 == arrFI.Length) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
IShellFolder oParentFolder = GetParentFolder(arrFI[0].Parent.FullName);
if (null == oParentFolder) {
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
IntPtr[] arrPIDLs = new IntPtr[arrFI.Length];
int n = 0;
foreach (DirectoryInfo fi in arrFI) {
// Get the file relative to folder
uint pchEaten = 0;
SFGAO pdwAttributes = 0;
IntPtr pPIDL = IntPtr.Zero;
int nResult = oParentFolder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, fi.Name, ref pchEaten, out pPIDL, ref pdwAttributes);
if (S_OK != nResult) {
FreePIDLs(arrPIDLs);
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
arrPIDLs[n] = pPIDL;
n++;
}
return arrPIDLs;
}
#endregion
#region FreePIDLs()
/// <summary>
/// Free the PIDLs
/// </summary>
/// <param name="arrPIDLs">Array of PIDLs (IntPtr)</param>
protected void FreePIDLs(IntPtr[] arrPIDLs) {
if (null != arrPIDLs) {
for (int n = 0; n < arrPIDLs.Length; n++) {
if (arrPIDLs[n] != IntPtr.Zero) {
Marshal.FreeCoTaskMem(arrPIDLs[n]);
arrPIDLs[n] = IntPtr.Zero;
}
}
}
}
#endregion
#region InvokeContextMenuDefault
private void InvokeContextMenuDefault(FileInfo[] arrFI) {
// Release all resources first.
ReleaseAll();
IntPtr pMenu = IntPtr.Zero,
iContextMenuPtr = IntPtr.Zero;
try {
_arrPIDLs = GetPIDLs(arrFI);
if (null == _arrPIDLs) {
ReleaseAll();
return;
}
if (false == GetContextMenuInterfaces(_oParentFolder, _arrPIDLs, out iContextMenuPtr)) {
ReleaseAll();
return;
}
pMenu = CreatePopupMenu();
int nResult = _oContextMenu.QueryContextMenu(
pMenu,
0,
CMD_FIRST,
CMD_LAST,
CMF.DEFAULTONLY |
( ( Control.ModifierKeys & Keys.Shift ) != 0 ? CMF.EXTENDEDVERBS : 0 ));
uint nDefaultCmd = (uint) GetMenuDefaultItem(pMenu, false, 0);
if (nDefaultCmd >= CMD_FIRST) {
InvokeCommand(_oContextMenu, nDefaultCmd, arrFI[0].DirectoryName, Control.MousePosition);
}
DestroyMenu(pMenu);
pMenu = IntPtr.Zero;
} catch {
throw;
} finally {
if (pMenu != IntPtr.Zero) {
DestroyMenu(pMenu);
}
ReleaseAll();
}
}
#endregion
#region ShowContextMenu()
/// <summary>
/// Shows the context menu
/// </summary>
/// <param name="files">FileInfos (should all be in same directory)</param>
/// <param name="pointScreen">Where to show the menu</param>
public void ShowContextMenu(FileInfo[] files, Point pointScreen) {
// Release all resources first.
ReleaseAll();
_arrPIDLs = GetPIDLs(files);
this.ShowContextMenu(pointScreen);
}
/// <summary>
/// Shows the context menu
/// </summary>
/// <param name="dirs">DirectoryInfos (should all be in same directory)</param>
/// <param name="pointScreen">Where to show the menu</param>
public void ShowContextMenu(DirectoryInfo[] dirs, Point pointScreen) {
// Release all resources first.
ReleaseAll();
_arrPIDLs = GetPIDLs(dirs);
this.ShowContextMenu(pointScreen);
}
#pragma warning disable CS1572 // XML comment has a param tag, but there is no parameter by that name
/// <summary>
/// Shows the context menu
/// </summary>
/// <param name="arrFI">FileInfos (should all be in same directory)</param>
/// <param name="pointScreen">Where to show the menu</param>
private void ShowContextMenu(Point pointScreen) {
IntPtr pMenu = IntPtr.Zero,
iContextMenuPtr = IntPtr.Zero,
iContextMenuPtr2 = IntPtr.Zero,
iContextMenuPtr3 = IntPtr.Zero;
try {
if (null == _arrPIDLs) {
ReleaseAll();
return;
}
if (false == GetContextMenuInterfaces(_oParentFolder, _arrPIDLs, out iContextMenuPtr)) {
ReleaseAll();
return;
}
pMenu = CreatePopupMenu();
int nResult = _oContextMenu.QueryContextMenu(
pMenu,
0,
CMD_FIRST,
CMD_LAST,
CMF.EXPLORE |
CMF.NORMAL |
( ( Control.ModifierKeys & Keys.Shift ) != 0 ? CMF.EXTENDEDVERBS : 0 ));
Marshal.QueryInterface(iContextMenuPtr, ref IID_IContextMenu2, out iContextMenuPtr2);
Marshal.QueryInterface(iContextMenuPtr, ref IID_IContextMenu3, out iContextMenuPtr3);
_oContextMenu2 = (IContextMenu2) Marshal.GetTypedObjectForIUnknown(iContextMenuPtr2, typeof(IContextMenu2));
_oContextMenu3 = (IContextMenu3) Marshal.GetTypedObjectForIUnknown(iContextMenuPtr3, typeof(IContextMenu3));
uint nSelected = TrackPopupMenuEx(
pMenu,
TPM.RETURNCMD,
pointScreen.X,
pointScreen.Y,
this.Handle,
IntPtr.Zero);
// First invoke menu item, then destroy menu.
if (nSelected != 0) {
InvokeCommand(_oContextMenu, nSelected, _strParentFolder, pointScreen);
}
DestroyMenu(pMenu);
pMenu = IntPtr.Zero;
} catch {
throw;
} finally {
//hook.Uninstall();
if (pMenu != IntPtr.Zero) {
DestroyMenu(pMenu);
}
if (iContextMenuPtr != IntPtr.Zero)
Marshal.Release(iContextMenuPtr);
if (iContextMenuPtr2 != IntPtr.Zero)
Marshal.Release(iContextMenuPtr2);
if (iContextMenuPtr3 != IntPtr.Zero)
Marshal.Release(iContextMenuPtr3);
ReleaseAll();
}
}
#pragma warning restore CS1572 // XML comment has a param tag, but there is no parameter by that name
#endregion
#region Local variabled
private IContextMenu _oContextMenu;
private IContextMenu2 _oContextMenu2;
private IContextMenu3 _oContextMenu3;
private IShellFolder _oDesktopFolder;
private IShellFolder _oParentFolder;
private IntPtr[] _arrPIDLs;
private string _strParentFolder;
#endregion
#region Variables and Constants
private const int MAX_PATH = 260;
private const uint CMD_FIRST = 1;
private const uint CMD_LAST = 30000;
private const int S_OK = 0;
private const int S_FALSE = 1;
private static int cbMenuItemInfo = Marshal.SizeOf(typeof(MENUITEMINFO));
private static int cbInvokeCommand = Marshal.SizeOf(typeof(CMINVOKECOMMANDINFOEX));
#endregion
#region DLL Import
// Retrieves the IShellFolder interface for the desktop folder, which is the root of the Shell's namespace.
[DllImport("shell32.dll")]
private static extern Int32 SHGetDesktopFolder(out IntPtr ppshf);
// Takes a STRRET structure returned by IShellFolder::GetDisplayNameOf, converts it to a string, and places the result in a buffer.
[DllImport("shlwapi.dll", EntryPoint = "StrRetToBuf", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern Int32 StrRetToBuf(IntPtr pstr, IntPtr pidl, StringBuilder pszBuf, int cchBuf);
// The TrackPopupMenuEx function displays a shortcut menu at the specified location and tracks the selection of items on the shortcut menu. The shortcut menu can appear anywhere on the screen.
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
private static extern uint TrackPopupMenuEx(IntPtr hmenu, TPM flags, int x, int y, IntPtr hwnd, IntPtr lptpm);
// The CreatePopupMenu function creates a drop-down menu, submenu, or shortcut menu. The menu is initially empty. You can insert or append menu items by using the InsertMenuItem function. You can also use the InsertMenu function to insert menu items and the AppendMenu function to append menu items.
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreatePopupMenu();
// The DestroyMenu function destroys the specified menu and frees any memory that the menu occupies.
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DestroyMenu(IntPtr hMenu);
// Determines the default menu item on the specified menu
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetMenuDefaultItem(IntPtr hMenu, bool fByPos, uint gmdiFlags);
#endregion
#region Shell GUIDs
private static Guid IID_IShellFolder = new Guid("{000214E6-0000-0000-C000-000000000046}");
private static Guid IID_IContextMenu = new Guid("{000214e4-0000-0000-c000-000000000046}");
private static Guid IID_IContextMenu2 = new Guid("{000214f4-0000-0000-c000-000000000046}");
private static Guid IID_IContextMenu3 = new Guid("{bcfce0a0-ec17-11d0-8d10-00a0c90f2719}");
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential)]
private struct CWPSTRUCT {
public IntPtr lparam;
public IntPtr wparam;
public int message;
public IntPtr hwnd;
}
// Contains extended information about a shortcut menu command
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CMINVOKECOMMANDINFOEX {
public int cbSize;
public CMIC fMask;
public IntPtr hwnd;
public IntPtr lpVerb;
[MarshalAs(UnmanagedType.LPStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPStr)]
public string lpDirectory;
public SW nShow;
public int dwHotKey;
public IntPtr hIcon;
[MarshalAs(UnmanagedType.LPStr)]
public string lpTitle;
public IntPtr lpVerbW;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpParametersW;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpDirectoryW;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpTitleW;
public POINT ptInvoke;
}
// Contains information about a menu item
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct MENUITEMINFO {
public MENUITEMINFO(string text) {
cbSize = cbMenuItemInfo;
dwTypeData = text;
cch = text.Length;
fMask = 0;
fType = 0;
fState = 0;
wID = 0;
hSubMenu = IntPtr.Zero;
hbmpChecked = IntPtr.Zero;
hbmpUnchecked = IntPtr.Zero;
dwItemData = IntPtr.Zero;
hbmpItem = IntPtr.Zero;
}
public int cbSize;
public MIIM fMask;
public MFT fType;
public MFS fState;
public uint wID;
public IntPtr hSubMenu;
public IntPtr hbmpChecked;
public IntPtr hbmpUnchecked;
public IntPtr dwItemData;
[MarshalAs(UnmanagedType.LPTStr)]
public string dwTypeData;
public int cch;
public IntPtr hbmpItem;
}
// A generalized global memory handle used for data transfer operations by the
// IAdviseSink, IDataObject, and IOleCache interfaces
[StructLayout(LayoutKind.Sequential)]
private struct STGMEDIUM {
public TYMED tymed;
public IntPtr hBitmap;
public IntPtr hMetaFilePict;
public IntPtr hEnhMetaFile;
public IntPtr hGlobal;
public IntPtr lpszFileName;
public IntPtr pstm;
public IntPtr pstg;
public IntPtr pUnkForRelease;
}
// Defines the x- and y-coordinates of a point
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct POINT {
public POINT(int x, int y) {
this.x = x;
this.y = y;
}
public int x;
public int y;
}
#endregion
#region Enums
// Defines the values used with the IShellFolder::GetDisplayNameOf and IShellFolder::SetNameOf
// methods to specify the type of file or folder names used by those methods
[Flags]
private enum SHGNO {
NORMAL = 0x0000,
INFOLDER = 0x0001,
FOREDITING = 0x1000,
FORADDRESSBAR = 0x4000,
FORPARSING = 0x8000
}
// The attributes that the caller is requesting, when calling IShellFolder::GetAttributesOf
[Flags]
private enum SFGAO : uint {
BROWSABLE = 0x8000000,
CANCOPY = 1,
CANDELETE = 0x20,
CANLINK = 4,
CANMONIKER = 0x400000,
CANMOVE = 2,
CANRENAME = 0x10,
CAPABILITYMASK = 0x177,
COMPRESSED = 0x4000000,
CONTENTSMASK = 0x80000000,
DISPLAYATTRMASK = 0xfc000,
DROPTARGET = 0x100,
ENCRYPTED = 0x2000,
FILESYSANCESTOR = 0x10000000,
FILESYSTEM = 0x40000000,
FOLDER = 0x20000000,
GHOSTED = 0x8000,
HASPROPSHEET = 0x40,
HASSTORAGE = 0x400000,
HASSUBFOLDER = 0x80000000,
HIDDEN = 0x80000,
ISSLOW = 0x4000,
LINK = 0x10000,
NEWCONTENT = 0x200000,
NONENUMERATED = 0x100000,
READONLY = 0x40000,
REMOVABLE = 0x2000000,
SHARE = 0x20000,
STORAGE = 8,
STORAGEANCESTOR = 0x800000,
STORAGECAPMASK = 0x70c50008,
STREAM = 0x400000,
VALIDATE = 0x1000000
}
// Determines the type of items included in an enumeration.
// These values are used with the IShellFolder::EnumObjects method
[Flags]
private enum SHCONTF {
FOLDERS = 0x0020,
NONFOLDERS = 0x0040,
INCLUDEHIDDEN = 0x0080,
INIT_ON_FIRST_NEXT = 0x0100,
NETPRINTERSRCH = 0x0200,
SHAREABLE = 0x0400,
STORAGE = 0x0800,
}
// Specifies how the shortcut menu can be changed when calling IContextMenu::QueryContextMenu
[Flags]
private enum CMF : uint {
NORMAL = 0x00000000,
DEFAULTONLY = 0x00000001,
VERBSONLY = 0x00000002,
EXPLORE = 0x00000004,
NOVERBS = 0x00000008,
CANRENAME = 0x00000010,
NODEFAULT = 0x00000020,
INCLUDESTATIC = 0x00000040,
EXTENDEDVERBS = 0x00000100,
RESERVED = 0xffff0000
}
// Flags specifying the information to return when calling IContextMenu::GetCommandString
[Flags]
private enum GCS : uint {
VERBA = 0,
HELPTEXTA = 1,
VALIDATEA = 2,
VERBW = 4,
HELPTEXTW = 5,
VALIDATEW = 6
}
// Specifies how TrackPopupMenuEx positions the shortcut menu horizontally
[Flags]
private enum TPM : uint {
LEFTBUTTON = 0x0000,
RIGHTBUTTON = 0x0002,
LEFTALIGN = 0x0000,
CENTERALIGN = 0x0004,
RIGHTALIGN = 0x0008,
TOPALIGN = 0x0000,
VCENTERALIGN = 0x0010,
BOTTOMALIGN = 0x0020,
HORIZONTAL = 0x0000,
VERTICAL = 0x0040,
NONOTIFY = 0x0080,
RETURNCMD = 0x0100,
RECURSE = 0x0001,
HORPOSANIMATION = 0x0400,
HORNEGANIMATION = 0x0800,
VERPOSANIMATION = 0x1000,
VERNEGANIMATION = 0x2000,
NOANIMATION = 0x4000,
LAYOUTRTL = 0x8000
}
// The cmd for a custom added menu item
private enum CMD_CUSTOM {
ExpandCollapse = (int) CMD_LAST + 1
}
// Flags used with the CMINVOKECOMMANDINFOEX structure
[Flags]
private enum CMIC : uint {
HOTKEY = 0x00000020,
ICON = 0x00000010,
FLAG_NO_UI = 0x00000400,
UNICODE = 0x00004000,
NO_CONSOLE = 0x00008000,
ASYNCOK = 0x00100000,
NOZONECHECKS = 0x00800000,
SHIFT_DOWN = 0x10000000,
CONTROL_DOWN = 0x40000000,
FLAG_LOG_USAGE = 0x04000000,
PTINVOKE = 0x20000000
}
// Specifies how the window is to be shown
[Flags]
private enum SW {
HIDE = 0,
SHOWNORMAL = 1,
NORMAL = 1,
SHOWMINIMIZED = 2,
SHOWMAXIMIZED = 3,
MAXIMIZE = 3,
SHOWNOACTIVATE = 4,
SHOW = 5,
MINIMIZE = 6,
SHOWMINNOACTIVE = 7,
SHOWNA = 8,
RESTORE = 9,
SHOWDEFAULT = 10,
}
// Window message flags
[Flags]
private enum WM : uint {
ACTIVATE = 0x6,
ACTIVATEAPP = 0x1C,
AFXFIRST = 0x360,
AFXLAST = 0x37F,
APP = 0x8000,
ASKCBFORMATNAME = 0x30C,
CANCELJOURNAL = 0x4B,
CANCELMODE = 0x1F,
CAPTURECHANGED = 0x215,
CHANGECBCHAIN = 0x30D,
CHAR = 0x102,
CHARTOITEM = 0x2F,
CHILDACTIVATE = 0x22,
CLEAR = 0x303,
CLOSE = 0x10,
COMMAND = 0x111,
COMPACTING = 0x41,
COMPAREITEM = 0x39,
CONTEXTMENU = 0x7B,
COPY = 0x301,
COPYDATA = 0x4A,
CREATE = 0x1,
CTLCOLORBTN = 0x135,
CTLCOLORDLG = 0x136,
CTLCOLOREDIT = 0x133,
CTLCOLORLISTBOX = 0x134,
CTLCOLORMSGBOX = 0x132,
CTLCOLORSCROLLBAR = 0x137,
CTLCOLORSTATIC = 0x138,
CUT = 0x300,
DEADCHAR = 0x103,
DELETEITEM = 0x2D,
DESTROY = 0x2,
DESTROYCLIPBOARD = 0x307,
DEVICECHANGE = 0x219,
DEVMODECHANGE = 0x1B,
DISPLAYCHANGE = 0x7E,
DRAWCLIPBOARD = 0x308,
DRAWITEM = 0x2B,
DROPFILES = 0x233,
ENABLE = 0xA,
ENDSESSION = 0x16,
ENTERIDLE = 0x121,
ENTERMENULOOP = 0x211,
ENTERSIZEMOVE = 0x231,
ERASEBKGND = 0x14,
EXITMENULOOP = 0x212,
EXITSIZEMOVE = 0x232,
FONTCHANGE = 0x1D,
GETDLGCODE = 0x87,
GETFONT = 0x31,
GETHOTKEY = 0x33,
GETICON = 0x7F,
GETMINMAXINFO = 0x24,
GETOBJECT = 0x3D,
GETSYSMENU = 0x313,
GETTEXT = 0xD,
GETTEXTLENGTH = 0xE,
HANDHELDFIRST = 0x358,
HANDHELDLAST = 0x35F,
HELP = 0x53,
HOTKEY = 0x312,
HSCROLL = 0x114,
HSCROLLCLIPBOARD = 0x30E,
ICONERASEBKGND = 0x27,
IME_CHAR = 0x286,
IME_COMPOSITION = 0x10F,
IME_COMPOSITIONFULL = 0x284,
IME_CONTROL = 0x283,
IME_ENDCOMPOSITION = 0x10E,
IME_KEYDOWN = 0x290,
IME_KEYLAST = 0x10F,
IME_KEYUP = 0x291,
IME_NOTIFY = 0x282,
IME_REQUEST = 0x288,
IME_SELECT = 0x285,
IME_SETCONTEXT = 0x281,
IME_STARTCOMPOSITION = 0x10D,
INITDIALOG = 0x110,
INITMENU = 0x116,
INITMENUPOPUP = 0x117,
INPUTLANGCHANGE = 0x51,
INPUTLANGCHANGEREQUEST = 0x50,
KEYDOWN = 0x100,
KEYFIRST = 0x100,
KEYLAST = 0x108,
KEYUP = 0x101,
KILLFOCUS = 0x8,
LBUTTONDBLCLK = 0x203,
LBUTTONDOWN = 0x201,
LBUTTONUP = 0x202,
LVM_GETEDITCONTROL = 0x1018,
LVM_SETIMAGELIST = 0x1003,
MBUTTONDBLCLK = 0x209,
MBUTTONDOWN = 0x207,
MBUTTONUP = 0x208,
MDIACTIVATE = 0x222,
MDICASCADE = 0x227,
MDICREATE = 0x220,
MDIDESTROY = 0x221,
MDIGETACTIVE = 0x229,
MDIICONARRANGE = 0x228,
MDIMAXIMIZE = 0x225,
MDINEXT = 0x224,
MDIREFRESHMENU = 0x234,
MDIRESTORE = 0x223,
MDISETMENU = 0x230,
MDITILE = 0x226,
MEASUREITEM = 0x2C,
MENUCHAR = 0x120,
MENUCOMMAND = 0x126,
MENUDRAG = 0x123,
MENUGETOBJECT = 0x124,
MENURBUTTONUP = 0x122,
MENUSELECT = 0x11F,
MOUSEACTIVATE = 0x21,
MOUSEFIRST = 0x200,
MOUSEHOVER = 0x2A1,
MOUSELAST = 0x20A,
MOUSELEAVE = 0x2A3,
MOUSEMOVE = 0x200,
MOUSEWHEEL = 0x20A,
MOVE = 0x3,
MOVING = 0x216,
NCACTIVATE = 0x86,
NCCALCSIZE = 0x83,
NCCREATE = 0x81,
NCDESTROY = 0x82,
NCHITTEST = 0x84,
NCLBUTTONDBLCLK = 0xA3,
NCLBUTTONDOWN = 0xA1,
NCLBUTTONUP = 0xA2,
NCMBUTTONDBLCLK = 0xA9,
NCMBUTTONDOWN = 0xA7,
NCMBUTTONUP = 0xA8,
NCMOUSEHOVER = 0x2A0,
NCMOUSELEAVE = 0x2A2,
NCMOUSEMOVE = 0xA0,
NCPAINT = 0x85,
NCRBUTTONDBLCLK = 0xA6,
NCRBUTTONDOWN = 0xA4,
NCRBUTTONUP = 0xA5,
NEXTDLGCTL = 0x28,
NEXTMENU = 0x213,
NOTIFY = 0x4E,
NOTIFYFORMAT = 0x55,
NULL = 0x0,
PAINT = 0xF,
PAINTCLIPBOARD = 0x309,
PAINTICON = 0x26,
PALETTECHANGED = 0x311,
PALETTEISCHANGING = 0x310,
PARENTNOTIFY = 0x210,
PASTE = 0x302,
PENWINFIRST = 0x380,
PENWINLAST = 0x38F,
POWER = 0x48,
PRINT = 0x317,
PRINTCLIENT = 0x318,
QUERYDRAGICON = 0x37,
QUERYENDSESSION = 0x11,
QUERYNEWPALETTE = 0x30F,
QUERYOPEN = 0x13,
QUEUESYNC = 0x23,
QUIT = 0x12,
RBUTTONDBLCLK = 0x206,