-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathExplorerIntegration.cs
248 lines (216 loc) · 7.09 KB
/
ExplorerIntegration.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
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Grepy2
{
public class ExplorerIntegration
{
/// <summary>
/// Passed to <see cref="GetTokenInformation"/> to specify what
/// information about the token to return.
/// </summary>
enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUiAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
/// <summary>
/// The elevation type for a user token.
/// </summary>
enum TokenElevationType
{
TokenElevationTypeDefault = 1,
TokenElevationTypeFull,
TokenElevationTypeLimited
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);
bool bIsAdministrator;
private bool IsUserAdministrator()
{
// http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/
var identity = WindowsIdentity.GetCurrent();
if (identity == null)
{
throw new InvalidOperationException("Couldn't get the current user identity");
}
var principal = new WindowsPrincipal(identity);
// Check if this user has the Administrator role. If they do, return immediately.
// If UAC is on, and the process is not elevated, then this will actually return false.
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
// If we're not running in Vista onwards, we don't have to worry about checking for UAC.
if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
{
// Operating system does not support UAC; skipping elevation check.
return false;
}
int tokenInfLength = Marshal.SizeOf(typeof(int));
IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);
try
{
var token = identity.Token;
var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);
if (!result)
{
var exception = Marshal.GetExceptionForHR( Marshal.GetHRForLastWin32Error() );
throw new InvalidOperationException("Couldn't get token information", exception);
}
var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);
switch (elevationType)
{
case TokenElevationType.TokenElevationTypeDefault:
// TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
return false;
case TokenElevationType.TokenElevationTypeFull:
// TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
return true;
case TokenElevationType.TokenElevationTypeLimited:
// TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
return true;
default:
// Unknown token elevation type.
return false;
}
}
finally
{
if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation);
}
}
public bool IsEnabled(string where)
{
if( where == "here" )
{
string regPath = string.Format(@"SOFTWARE\Classes\Directory\Background\shell\Grepy2");
try
{
return Registry.LocalMachine.OpenSubKey(regPath) != null;
}
catch( UnauthorizedAccessException )
{
return false;
}
}
else
{
string regPath = string.Format(@"{0}\shell\Grepy2", where);
try
{
return Registry.ClassesRoot.OpenSubKey(regPath) != null;
}
catch( UnauthorizedAccessException )
{
return false;
}
}
}
public void Enable(string where, string ApplicationExePath)
{
try
{
if( where == "here" )
{
string regPath = string.Format(@"SOFTWARE\Classes\Directory\Background\shell\Grepy2");
RegistryKey keyName = Registry.LocalMachine.CreateSubKey(regPath);
keyName.SetValue(null, "Grepy2...");
RegistryKey keyIcon = Registry.LocalMachine.CreateSubKey(string.Format(@"{0}", regPath));
keyIcon.SetValue("Icon", ApplicationExePath);
string command = string.Format("\"{0}\" \"%V\"", ApplicationExePath);
RegistryKey keyCommand = Registry.LocalMachine.CreateSubKey(string.Format(@"{0}\command", regPath));
keyCommand.SetValue(null, command);
}
else
{
string regPath = string.Format(@"{0}\shell\Grepy2", where);
RegistryKey keyName = Registry.ClassesRoot.CreateSubKey(regPath);
keyName.SetValue(null, "Grepy2...");
RegistryKey keyIcon = Registry.ClassesRoot.CreateSubKey(string.Format(@"{0}", regPath));
keyIcon.SetValue("Icon", ApplicationExePath);
string command = string.Format("\"{0}\" \"%1\"", ApplicationExePath);
RegistryKey keyCommand = Registry.ClassesRoot.CreateSubKey(string.Format(@"{0}\command", regPath));
keyCommand.SetValue(null, command);
}
}
catch
{
bIsAdministrator = false;
}
}
public void Disable(string where, string ApplicationExePath)
{
try
{
if( where == "here" )
{
string regPath = string.Format(@"SOFTWARE\Classes\Directory\Background\shell\Grepy2");
Registry.LocalMachine.DeleteSubKeyTree(regPath);
}
else
{
string regPath = string.Format(@"{0}\shell\Grepy2", where);
Registry.ClassesRoot.DeleteSubKeyTree(regPath);
}
}
catch
{
bIsAdministrator = false;
}
}
public void Set(string PathExe, bool bEnable)
{
bIsAdministrator = IsUserAdministrator();
if( bIsAdministrator )
{
if( bEnable )
{
Enable("Drive", PathExe); // right clicking on a Disk (drive, like C:)
Enable("Directory", PathExe); // right clicking on a folder (this can be a folder in the navigation pane on the left or in the file pane on the right)
Enable("here", PathExe); // right clicking on the empty part of a folder in the file pane (i.e. use the folder I am clicking inside of)
}
else
{
Disable("Drive", PathExe);
Disable("Directory", PathExe);
Disable("here", PathExe); // right clicking on the empty part of a folder
}
}
if( !bIsAdministrator )
{
MessageBox.Show("You need to run this program with Administrator Privileges to change Windows Explorer Integration.\n\n(Right click on the Grepy icon in the Start menu or on the desktop shortcut and select \"Run as administrator\" or \"More -> Run as administrator\".)",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
}