forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Win32API.cs
289 lines (260 loc) · 10.9 KB
/
Win32API.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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
using Windows.Foundation.Collections;
using Windows.System;
namespace FilesFullTrust
{
internal partial class Win32API
{
public static Task<T> StartSTATask<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
Thread thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception ex)
{
tcs.SetResult(default);
NLog.LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
//tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
public static async Task<string> GetFileAssociationAsync(string filename)
{
// Find UWP apps
var uwpApps = await Launcher.FindFileHandlersAsync(Path.GetExtension(filename));
if (uwpApps.Any())
{
return uwpApps.First().PackageFamilyName;
}
// Find desktop apps
var lpResult = new StringBuilder(2048);
var hResult = Shell32.FindExecutable(filename, null, lpResult);
if (hResult.ToInt64() > 32)
{
return lpResult.ToString();
}
return null;
}
public static string ExtractStringFromDLL(string file, int number)
{
var lib = Kernel32.LoadLibrary(file);
StringBuilder result = new StringBuilder(2048);
User32.LoadString(lib, number, result, result.Capacity);
Kernel32.FreeLibrary(lib);
return result.ToString();
}
public static string[] CommandLineToArgs(string commandLine)
{
if (string.IsNullOrEmpty(commandLine))
{
return Array.Empty<string>();
}
var argv = Shell32.CommandLineToArgvW(commandLine, out int argc);
if (argv == IntPtr.Zero)
{
throw new Win32Exception();
}
try
{
var args = new string[argc];
for (var i = 0; i < args.Length; i++)
{
var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
args[i] = Marshal.PtrToStringUni(p);
}
return args;
}
finally
{
Marshal.FreeHGlobal(argv);
}
}
public static (string icon, string overlay, bool isCustom) GetFileIconAndOverlay(string path, int thumbnailSize)
{
string iconStr = null, overlayStr = null;
using var shellItem = new Vanara.Windows.Shell.ShellItem(path);
if (shellItem.IShellItem is Shell32.IShellItemImageFactory fctry)
{
var flags = Shell32.SIIGBF.SIIGBF_BIGGERSIZEOK;
if (thumbnailSize < 80) flags |= Shell32.SIIGBF.SIIGBF_ICONONLY;
var hres = fctry.GetImage(new SIZE(thumbnailSize, thumbnailSize), flags, out var hbitmap);
if (hres == HRESULT.S_OK)
{
using var image = GetBitmapFromHBitmap(hbitmap);
if (image != null)
{
byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
iconStr = Convert.ToBase64String(bitmapData, 0, bitmapData.Length);
}
}
//Marshal.ReleaseComObject(fctry);
}
var shfi = new Shell32.SHFILEINFO();
var ret = Shell32.SHGetFileInfo(
path,
0,
ref shfi,
Shell32.SHFILEINFO.Size,
Shell32.SHGFI.SHGFI_OVERLAYINDEX | Shell32.SHGFI.SHGFI_ICON | Shell32.SHGFI.SHGFI_SYSICONINDEX | Shell32.SHGFI.SHGFI_ICONLOCATION);
if (ret == IntPtr.Zero)
{
return (iconStr, null, false);
}
bool isCustom = !shfi.szDisplayName.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
User32.DestroyIcon(shfi.hIcon);
Shell32.SHGetImageList(Shell32.SHIL.SHIL_LARGE, typeof(ComCtl32.IImageList).GUID, out var tmp);
using var imageList = ComCtl32.SafeHIMAGELIST.FromIImageList(tmp);
if (imageList.IsNull || imageList.IsInvalid)
{
return (iconStr, null, isCustom);
}
var overlayIdx = shfi.iIcon >> 24;
if (overlayIdx != 0)
{
var overlayImage = imageList.Interface.GetOverlayImage(overlayIdx);
using var hOverlay = imageList.Interface.GetIcon(overlayImage, ComCtl32.IMAGELISTDRAWFLAGS.ILD_TRANSPARENT);
if (!hOverlay.IsNull && !hOverlay.IsInvalid)
{
using var image = hOverlay.ToIcon().ToBitmap();
byte[] bitmapData = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
overlayStr = Convert.ToBase64String(bitmapData, 0, bitmapData.Length);
}
}
return (iconStr, overlayStr, isCustom);
}
private static void RunPowershellCommand(string command, bool runAsAdmin)
{
try
{
using Process process = new Process();
if (runAsAdmin)
{
process.StartInfo.UseShellExecute = true;
process.StartInfo.Verb = "runas";
}
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Arguments = command;
process.Start();
process.WaitForExit(30 * 1000);
}
catch (Win32Exception)
{
// If user cancels UAC
}
}
public static void UnlockBitlockerDrive(string drive, string password)
{
RunPowershellCommand($"-command \"$SecureString = ConvertTo-SecureString '{password}' -AsPlainText -Force; Unlock-BitLocker -MountPoint '{drive}' -Password $SecureString\"", true);
}
public static void OpenFormatDriveDialog(string drive)
{
// format requires elevation
int driveIndex = drive.ToUpperInvariant()[0] - 'A';
RunPowershellCommand($"-command \"$Signature = '[DllImport(\\\"shell32.dll\\\", SetLastError = false)]public static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID, uint options);'; $SHFormatDrive = Add-Type -MemberDefinition $Signature -Name \"Win32SHFormatDrive\" -Namespace Win32Functions -PassThru; $SHFormatDrive::SHFormatDrive(0, {driveIndex}, 0xFFFF, 0x0001)\"", true);
}
public static void SetVolumeLabel(string driveName, string newLabel)
{
// rename requires elevation
RunPowershellCommand($"-command \"$Signature = '[DllImport(\\\"kernel32.dll\\\", SetLastError = false)]public static extern bool SetVolumeLabel(string lpRootPathName, string lpVolumeName);'; $SetVolumeLabel = Add-Type -MemberDefinition $Signature -Name \"Win32SetVolumeLabel\" -Namespace Win32Functions -PassThru; $SetVolumeLabel::SetVolumeLabel('{driveName}', '{newLabel}')\"", true);
}
private static Bitmap GetBitmapFromHBitmap(HBITMAP hBitmap)
{
try
{
Bitmap bmp = Image.FromHbitmap((IntPtr)hBitmap);
if (Image.GetPixelFormatSize(bmp.PixelFormat) < 32)
{
return bmp;
}
if (IsAlphaBitmap(bmp, out var bmpData))
{
return GetAlphaBitmapFromBitmapData(bmpData);
}
return bmp;
}
catch
{
return null;
}
}
private static Bitmap GetAlphaBitmapFromBitmapData(BitmapData bmpData)
{
return new Bitmap(
bmpData.Width,
bmpData.Height,
bmpData.Stride,
PixelFormat.Format32bppArgb,
bmpData.Scan0);
}
private static bool IsAlphaBitmap(Bitmap bmp, out BitmapData bmpData)
{
Rectangle bmBounds = new Rectangle(0, 0, bmp.Width, bmp.Height);
bmpData = bmp.LockBits(bmBounds, ImageLockMode.ReadOnly, bmp.PixelFormat);
try
{
for (int y = 0; y <= bmpData.Height - 1; y++)
{
for (int x = 0; x <= bmpData.Width - 1; x++)
{
Color pixelColor = Color.FromArgb(
Marshal.ReadInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x)));
if (pixelColor.A > 0 & pixelColor.A < 255)
{
return true;
}
}
}
}
finally
{
bmp.UnlockBits(bmpData);
}
return false;
}
public static async Task SendMessageAsync(NamedPipeServerStream pipe, ValueSet valueSet, string requestID = null)
{
var message = new Dictionary<string, object>(valueSet);
message.Add("RequestID", requestID);
var serialized = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
await pipe.WriteAsync(serialized, 0, serialized.Length);
}
// There is usually no need to define Win32 COM interfaces/P-Invoke methods here.
// The Vanara library contains the definitions for all members of Shell32.dll, User32.dll and more
// The ones below are due to bugs in the current version of the library and can be removed once fixed
// Structure used by SHQueryRecycleBin.
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct SHQUERYRBINFO
{
public int cbSize;
public long i64Size;
public long i64NumItems;
}
// Get information from recycle bin.
[DllImport(Lib.Shell32, SetLastError = false, CharSet = CharSet.Auto)]
public static extern int SHQueryRecycleBin(string pszRootPath,
ref SHQUERYRBINFO pSHQueryRBInfo);
}
}