-
Notifications
You must be signed in to change notification settings - Fork 290
/
UnsafeNativeMethods.cs
562 lines (451 loc) · 18.8 KB
/
UnsafeNativeMethods.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
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and WPF UI Contributors.
// All Rights Reserved.
// This Source Code is partially based on reverse engineering of the Windows Operating System,
// and is intended for use on Windows systems only.
// This Source Code is partially based on the source code provided by the .NET Foundation.
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Wpf.Ui.Controls;
using Wpf.Ui.Hardware;
namespace Wpf.Ui.Interop;
/// <summary>
/// A set of dangerous methods to modify the appearance.
/// </summary>
public static class UnsafeNativeMethods
{
/// <summary>
/// Tries to set the <see cref="Window"/> corner preference.
/// </summary>
/// <param name="window">Selected window.</param>
/// <param name="cornerPreference">Window corner preference.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowCornerPreference(Window window, WindowCornerPreference cornerPreference) =>
GetHandle(window, out IntPtr windowHandle)
&& ApplyWindowCornerPreference(windowHandle, cornerPreference);
/// <summary>
/// Tries to set the corner preference of the selected window.
/// </summary>
/// <param name="handle">Selected window handle.</param>
/// <param name="cornerPreference">Window corner preference.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowCornerPreference(IntPtr handle, WindowCornerPreference cornerPreference)
{
if (handle == IntPtr.Zero)
return false;
if (!User32.IsWindow(handle))
return false;
int pvAttribute = (int) UnsafeReflection.Cast(cornerPreference);
// TODO: Validate HRESULT
Dwmapi.DwmSetWindowAttribute(
handle,
Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE,
ref pvAttribute,
Marshal.SizeOf(typeof(int))
);
return true;
}
/// <summary>
/// Tries to remove ImmersiveDarkMode effect from the <see cref="Window"/>.
/// </summary>
/// <param name="window">The window to which the effect is to be applied.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool RemoveWindowDarkMode(Window? window) =>
GetHandle(window, out IntPtr windowHandle) && RemoveWindowDarkMode(windowHandle);
/// <summary>
/// Tries to remove ImmersiveDarkMode effect from the window handle.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool RemoveWindowDarkMode(IntPtr handle)
{
if (handle == IntPtr.Zero)
return false;
if (!User32.IsWindow(handle))
return false;
var pvAttribute = 0x0; // Disable
var dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_USE_IMMERSIVE_DARK_MODE;
if (!Win32.Utilities.IsOSWindows11Insider1OrNewer)
dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DMWA_USE_IMMERSIVE_DARK_MODE_OLD;
// TODO: Validate HRESULT
Dwmapi.DwmSetWindowAttribute(handle, dwAttribute, ref pvAttribute, Marshal.SizeOf(typeof(int)));
return true;
}
/// <summary>
/// Tries to apply ImmersiveDarkMode effect for the <see cref="Window"/>.
/// </summary>
/// <param name="window">The window to which the effect is to be applied.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowDarkMode(Window? window) =>
GetHandle(window, out IntPtr windowHandle) && ApplyWindowDarkMode(windowHandle);
/// <summary>
/// Tries to apply ImmersiveDarkMode effect for the window handle.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowDarkMode(IntPtr handle)
{
if (handle == IntPtr.Zero)
return false;
if (!User32.IsWindow(handle))
return false;
var pvAttribute = 0x1; // Enable
var dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_USE_IMMERSIVE_DARK_MODE;
if (!Win32.Utilities.IsOSWindows11Insider1OrNewer)
dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DMWA_USE_IMMERSIVE_DARK_MODE_OLD;
// TODO: Validate HRESULT
Dwmapi.DwmSetWindowAttribute(handle, dwAttribute, ref pvAttribute, Marshal.SizeOf(typeof(int)));
return true;
}
/// <summary>
/// Tries to remove titlebar from selected <see cref="Window"/>.
/// </summary>
/// <param name="window">The window to which the effect is to be applied.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool RemoveWindowTitlebarContents(Window? window)
{
if (window == null)
return false;
if (window.IsLoaded)
return GetHandle(window, out IntPtr windowHandle) && RemoveWindowTitlebarContents(windowHandle);
window.Loaded += (sender, _) =>
{
GetHandle(sender as Window, out IntPtr windowHandle);
RemoveWindowTitlebarContents(windowHandle);
};
return true;
}
/// <summary>
/// Tries to remove titlebar from selected window handle.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool RemoveWindowTitlebarContents(IntPtr handle)
{
if (handle == IntPtr.Zero)
return false;
if (!User32.IsWindow(handle))
return false;
var windowStyleLong = User32.GetWindowLong(handle, User32.GWL.GWL_STYLE);
windowStyleLong &= ~(int) User32.WS.SYSMENU;
var result = SetWindowLong(handle, User32.GWL.GWL_STYLE, windowStyleLong);
return result.ToInt64() > 0x0;
}
/// <summary>
/// Tries to apply selected backdrop type for window handle.
/// </summary>
/// <param name="handle">Selected window handle.</param>
/// <param name="backgroundType">Backdrop type.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowBackdrop(IntPtr handle, WindowBackdropType backgroundType)
{
if (handle == IntPtr.Zero)
return false;
if (!User32.IsWindow(handle))
return false;
var backdropPvAttribute = (int) UnsafeReflection.Cast(backgroundType);
if (backdropPvAttribute == (int) Dwmapi.DWMSBT.DWMSBT_DISABLE)
return false;
// TODO: Validate HRESULT
Dwmapi.DwmSetWindowAttribute(
handle,
Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_SYSTEMBACKDROP_TYPE,
ref backdropPvAttribute,
Marshal.SizeOf(typeof(int))
);
return true;
}
/// <summary>
/// Tries to determine whether the provided <see cref="Window"/> has applied legacy backdrop effect.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <param name="backdropType">Background backdrop type.</param>
public static bool IsWindowHasBackdrop(IntPtr handle, WindowBackdropType backdropType)
{
if (!User32.IsWindow(handle))
return false;
var pvAttribute = 0x0;
Dwmapi.DwmGetWindowAttribute(
handle,
Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_SYSTEMBACKDROP_TYPE,
ref pvAttribute,
Marshal.SizeOf(typeof(int))
);
return pvAttribute == (int) UnsafeReflection.Cast(backdropType);
}
/// <summary>
/// Tries to determine whether the provided <see cref="Window"/> has applied legacy Mica effect.
/// </summary>
/// <param name="window">Window to check.</param>
public static bool IsWindowHasLegacyMica(Window? window) =>
GetHandle(window, out IntPtr windowHandle) && IsWindowHasLegacyMica(windowHandle);
/// <summary>
/// Tries to determine whether the provided handle has applied legacy Mica effect.
/// </summary>
/// <param name="handle">Window handle.</param>
public static bool IsWindowHasLegacyMica(IntPtr handle)
{
if (!User32.IsWindow(handle))
return false;
var pvAttribute = 0x0;
Dwmapi.DwmGetWindowAttribute(
handle,
Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_MICA_EFFECT,
ref pvAttribute,
Marshal.SizeOf(typeof(int))
);
return pvAttribute == 0x1;
}
/// <summary>
/// Tries to apply legacy Mica effect for the selected <see cref="Window"/>.
/// </summary>
/// <param name="window">The window to which the effect is to be applied.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowLegacyMicaEffect(Window? window) =>
GetHandle(window, out IntPtr windowHandle) && ApplyWindowLegacyMicaEffect(windowHandle);
/// <summary>
/// Tries to apply legacy Mica effect for the selected <see cref="Window"/>.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowLegacyMicaEffect(IntPtr handle)
{
var backdropPvAttribute = 0x1; //Enable
// TODO: Validate HRESULT
Dwmapi.DwmSetWindowAttribute(
handle,
Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_MICA_EFFECT,
ref backdropPvAttribute,
Marshal.SizeOf(typeof(int))
);
return true;
}
/// <summary>
/// Tries to apply legacy Acrylic effect for the selected <see cref="Window"/>.
/// </summary>
/// <param name="window">The window to which the effect is to be applied.</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowLegacyAcrylicEffect(Window? window) =>
GetHandle(window, out IntPtr windowHandle) && ApplyWindowLegacyAcrylicEffect(windowHandle);
/// <summary>
/// Tries to apply legacy Acrylic effect for the selected <see cref="Window"/>.
/// </summary>
/// <param name="handle">Window handle</param>
/// <returns><see langword="true"/> if invocation of native Windows function succeeds.</returns>
public static bool ApplyWindowLegacyAcrylicEffect(IntPtr handle)
{
var accentPolicy = new Interop.User32.ACCENT_POLICY
{
nAccentState = User32.ACCENT_STATE.ACCENT_ENABLE_ACRYLICBLURBEHIND,
nColor = 0x990000 & 0xFFFFFF
};
var accentStructSize = Marshal.SizeOf(accentPolicy);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accentPolicy, accentPtr, false);
var data = new User32.WINCOMPATTRDATA
{
Attribute = User32.WCA.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
User32.SetWindowCompositionAttribute(handle, ref data);
Marshal.FreeHGlobal(accentPtr);
return true;
}
/// <summary>
/// Tries to get currently selected Window accent color.
/// </summary>
public static Color GetDwmColor()
{
try
{
Dwmapi.DwmGetColorizationParameters(out var dwmParams);
var values = BitConverter.GetBytes(dwmParams.clrColor);
return Color.FromArgb(255, values[2], values[1], values[0]);
}
catch
{
var colorizationColorValue = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationColor", null);
if (colorizationColorValue is not null)
{
try
{
var colorizationColor = (uint)(int)colorizationColorValue;
var values = BitConverter.GetBytes(colorizationColor);
return Color.FromArgb(255, values[2], values[1], values[0]);
}
catch
{
}
}
}
return GetDefaultWindowsAccentColor();
}
/// <summary>
/// Tries to set taskbar state for the selected window handle.
/// </summary>
/// <param name="hWnd">Window handle.</param>
/// <param name="taskbarFlag">Taskbar flag.</param>
internal static bool SetTaskbarState(IntPtr hWnd, ShObjIdl.TBPFLAG taskbarFlag)
{
if (hWnd == IntPtr.Zero)
return false;
if (!User32.IsWindow(hWnd))
return false;
var taskbarList = new ShObjIdl.CTaskbarList() as ShObjIdl.ITaskbarList4;
if (taskbarList == null)
return false;
taskbarList.HrInit();
taskbarList.SetProgressState(hWnd, taskbarFlag);
return true;
}
/// <summary>
/// Tries to set taskbar value for the selected window handle.
/// </summary>
/// <param name="hWnd">Window handle.</param>
/// <param name="current">Current value.</param>
/// <param name="total">Total value to divide.</param>
internal static bool SetTaskbarValue(IntPtr hWnd, ShObjIdl.TBPFLAG taskbarFlag, int current, int total)
{
if (hWnd == IntPtr.Zero)
return false;
if (!User32.IsWindow(hWnd))
return false;
// TODO: Get existing taskbar class
var taskbarList = new ShObjIdl.CTaskbarList() as ShObjIdl.ITaskbarList4;
if (taskbarList == null)
return false;
taskbarList.HrInit();
taskbarList.SetProgressState(hWnd, taskbarFlag);
if (
taskbarFlag != ShObjIdl.TBPFLAG.TBPF_INDETERMINATE
&& taskbarFlag != ShObjIdl.TBPFLAG.TBPF_NOPROGRESS
)
taskbarList.SetProgressValue(hWnd, Convert.ToUInt64(current), Convert.ToUInt64(total));
return true;
}
public static bool RemoveWindowCaption(Window window)
{
if (window == null)
return false;
var windowHandle = new WindowInteropHelper(window).Handle;
return RemoveWindowCaption(windowHandle);
}
public static bool RemoveWindowCaption(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
return false;
if (!User32.IsWindow(hWnd))
return false;
var wtaOptions = new UxTheme.WTA_OPTIONS()
{
dwFlags = UxTheme.WTNCA.NODRAWCAPTION,
dwMask = UxTheme.WTNCA.VALIDBITS
};
UxTheme.SetWindowThemeAttribute(
hWnd,
UxTheme.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT,
ref wtaOptions,
(uint) Marshal.SizeOf(typeof(UxTheme.WTA_OPTIONS))
);
return true;
}
public static bool ExtendClientAreaIntoTitleBar(Window window)
{
if (window == null)
return false;
var windowHandle = new WindowInteropHelper(window).Handle;
return ExtendClientAreaIntoTitleBar(windowHandle);
}
public static bool ExtendClientAreaIntoTitleBar(IntPtr hWnd)
{
// !! EXPERIMENTAl
// NOTE:
// WinRt has ExtendContentIntoTitlebar, but it needs some digging
if (hWnd == IntPtr.Zero)
return false;
if (!User32.IsWindow(hWnd))
return false;
// #1 Remove titlebar elements
var wtaOptions = new UxTheme.WTA_OPTIONS()
{
dwFlags = (UxTheme.WTNCA.NODRAWCAPTION | UxTheme.WTNCA.NODRAWICON | UxTheme.WTNCA.NOSYSMENU),
dwMask = UxTheme.WTNCA.VALIDBITS
};
Interop
.UxTheme
.SetWindowThemeAttribute(
hWnd,
UxTheme.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT,
ref wtaOptions,
(uint) Marshal.SizeOf(typeof(UxTheme.WTA_OPTIONS))
);
var windowDpi = DpiHelper.GetWindowDpi(hWnd);
// #2 Extend glass frame
var deviceGlassThickness = DpiHelper.LogicalThicknessToDevice(
new Thickness(-1, -1, -1, -1),
windowDpi.DpiScaleX,
windowDpi.DpiScaleY
);
var dwmMargin = new UxTheme.MARGINS
{
// err on the side of pushing in glass an extra pixel.
cxLeftWidth = (int) Math.Ceiling(deviceGlassThickness.Left),
cxRightWidth = (int) Math.Ceiling(deviceGlassThickness.Right),
cyTopHeight = (int) Math.Ceiling(deviceGlassThickness.Top),
cyBottomHeight = (int) Math.Ceiling(deviceGlassThickness.Bottom),
};
// #3 Extend client area
Interop.Dwmapi.DwmExtendFrameIntoClientArea(hWnd, ref dwmMargin);
// #4 Clear rounding region
Interop.User32.SetWindowRgn(hWnd, IntPtr.Zero, Interop.User32.IsWindowVisible(hWnd));
return true;
}
/// <summary>
/// Checks whether the DWM composition is enabled.
/// </summary>
/// <returns></returns>
public static bool IsCompositionEnabled()
{
Dwmapi.DwmIsCompositionEnabled(out var isEnabled);
return isEnabled == 0x1;
}
/// <summary>
/// Checks if provided pointer represents existing window.
/// </summary>
public static bool IsValidWindow(IntPtr hWnd)
{
return User32.IsWindow(hWnd);
}
/// <summary>
/// Tries to get the pointer to the window handle.
/// </summary>
/// <param name="window"></param>
/// <param name="windowHandle"></param>
/// <returns><see langword="true"/> if the handle is not <see cref="IntPtr.Zero"/>.</returns>
private static bool GetHandle(Window? window, out IntPtr windowHandle)
{
if (window == null)
{
windowHandle = IntPtr.Zero;
return false;
}
windowHandle = new WindowInteropHelper(window).Handle;
return windowHandle != IntPtr.Zero;
}
private static IntPtr SetWindowLong(IntPtr handle, User32.GWL nIndex, long windowStyleLong)
{
if (IntPtr.Size == 4)
{
return new IntPtr(User32.SetWindowLong(handle, (int)nIndex, (int)windowStyleLong));
}
return User32.SetWindowLongPtr(handle, (int)nIndex, (IntPtr)windowStyleLong);
}
private static Color GetDefaultWindowsAccentColor()
{
// Windows default accent color
// https://learn.microsoft.com/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-themes-windowcolor#values
return Color.FromArgb(0xff, 0x00, 0x78, 0xd7);
}
}