├── DesktopWindowDemo
├── Assets
│ ├── WinUI3.ico
│ ├── StoreLogo.png
│ ├── SplashScreen.scale-200.png
│ ├── LockScreenLogo.scale-200.png
│ ├── Square44x44Logo.scale-200.png
│ ├── Wide310x150Logo.scale-200.png
│ ├── Square150x150Logo.scale-200.png
│ └── Square44x44Logo.targetsize-24_altform-unplated.png
├── Properties
│ └── launchSettings.json
├── App.xaml
├── app.manifest
├── Package.appxmanifest
├── App.xaml.cs
├── DesktopWindowDemo.csproj
├── MainWindow.xaml
└── MainWindow.xaml.cs
├── WindowExtensions
├── WindowExtensions.csproj
├── DisplayInformation.cs
└── DesktopWindow.cs
├── .gitattributes
├── DesktopWindowSample.sln
├── README.md
└── .gitignore
/DesktopWindowDemo/Assets/WinUI3.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/WinUI3.ico
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/StoreLogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/StoreLogo.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/SplashScreen.scale-200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/SplashScreen.scale-200.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/LockScreenLogo.scale-200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/LockScreenLogo.scale-200.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/Square44x44Logo.scale-200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/Square44x44Logo.scale-200.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/Wide310x150Logo.scale-200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/Wide310x150Logo.scale-200.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/Square150x150Logo.scale-200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/Square150x150Logo.scale-200.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Assets/Square44x44Logo.targetsize-24_altform-unplated.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marb2000/DesktopWindow/HEAD/DesktopWindowDemo/Assets/Square44x44Logo.targetsize-24_altform-unplated.png
--------------------------------------------------------------------------------
/DesktopWindowDemo/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "DesktopWindowDemo (Package)": {
4 | "commandName": "MsixPackage"
5 | },
6 | "DesktopWindowDemo (Unpackaged)": {
7 | "commandName": "Project"
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/DesktopWindowDemo/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 | true/PM
12 | PerMonitorV2, PerMonitor
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/WindowExtensions/WindowExtensions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0-windows10.0.19041.0
4 | 10.0.17763.0
5 | WindowExtensions
6 | win10-x86;win10-x64;win10-arm64
7 | true
8 |
9 |
10 |
11 | true
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/Package.appxmanifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
13 |
14 |
15 | DesktopWindowDemo
16 | migue
17 | Assets\StoreLogo.png
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
33 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.UI.Xaml;
2 | using Microsoft.UI.Xaml.Controls;
3 | using Microsoft.UI.Xaml.Controls.Primitives;
4 | using Microsoft.UI.Xaml.Data;
5 | using Microsoft.UI.Xaml.Input;
6 | using Microsoft.UI.Xaml.Media;
7 | using Microsoft.UI.Xaml.Navigation;
8 | using Microsoft.UI.Xaml.Shapes;
9 | using System;
10 | using System.Collections.Generic;
11 | using System.IO;
12 | using System.Linq;
13 | using System.Runtime.InteropServices.WindowsRuntime;
14 | using Windows.ApplicationModel;
15 | using Windows.ApplicationModel.Activation;
16 | using Windows.Foundation;
17 | using Windows.Foundation.Collections;
18 |
19 | // To learn more about WinUI, the WinUI project structure,
20 | // and more about our project templates, see: http://aka.ms/winui-project-info.
21 |
22 | namespace DesktopWindowDemo
23 | {
24 | ///
25 | /// Provides application-specific behavior to supplement the default Application class.
26 | ///
27 | public partial class App : Application
28 | {
29 | ///
30 | /// Initializes the singleton application object. This is the first line of authored code
31 | /// executed, and as such is the logical equivalent of main() or WinMain().
32 | ///
33 | public App()
34 | {
35 | this.InitializeComponent();
36 | }
37 |
38 | ///
39 | /// Invoked when the application is launched normally by the end user. Other entry points
40 | /// will be used such as when the application is launched to open a specific file.
41 | ///
42 | /// Details about the launch request and process.
43 | protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
44 | {
45 | m_window = new MainWindow();
46 | m_window.Activate();
47 | }
48 |
49 | private Window m_window;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/DesktopWindowDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | WinExe
4 | net6.0-windows10.0.19041.0
5 | 10.0.17763.0
6 | DesktopWindowDemo
7 | app.manifest
8 | x86;x64;arm64
9 | win10-x86;win10-x64;win10-arm64
10 | win10-$(Platform).pubxml
11 | true
12 | true
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
20 |
21 |
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 |
--------------------------------------------------------------------------------
/DesktopWindowSample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.2.32414.248
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WindowExtensions", "WindowExtensions\WindowExtensions.csproj", "{6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopWindowDemo", "DesktopWindowDemo\DesktopWindowDemo.csproj", "{06336E8A-1942-4F75-A8B0-6720786EA45E}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Debug|arm64 = Debug|arm64
14 | Debug|x64 = Debug|x64
15 | Debug|x86 = Debug|x86
16 | Release|Any CPU = Release|Any CPU
17 | Release|arm64 = Release|arm64
18 | Release|x64 = Release|x64
19 | Release|x86 = Release|x86
20 | EndGlobalSection
21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
22 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|arm64.ActiveCfg = Debug|Any CPU
25 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|arm64.Build.0 = Debug|Any CPU
26 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|x64.ActiveCfg = Debug|Any CPU
27 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|x64.Build.0 = Debug|Any CPU
28 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|x86.ActiveCfg = Debug|Any CPU
29 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Debug|x86.Build.0 = Debug|Any CPU
30 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|arm64.ActiveCfg = Release|Any CPU
33 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|arm64.Build.0 = Release|Any CPU
34 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|x64.ActiveCfg = Release|Any CPU
35 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|x64.Build.0 = Release|Any CPU
36 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|x86.ActiveCfg = Release|Any CPU
37 | {6FB3A02C-2E51-446D-A1D6-82BA9DCC7C53}.Release|x86.Build.0 = Release|Any CPU
38 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|Any CPU.ActiveCfg = Debug|x64
39 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|Any CPU.Build.0 = Debug|x64
40 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|Any CPU.Deploy.0 = Debug|x64
41 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|arm64.ActiveCfg = Debug|arm64
42 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|arm64.Build.0 = Debug|arm64
43 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|arm64.Deploy.0 = Debug|arm64
44 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x64.ActiveCfg = Debug|x64
45 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x64.Build.0 = Debug|x64
46 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x64.Deploy.0 = Debug|x64
47 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x86.ActiveCfg = Debug|x86
48 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x86.Build.0 = Debug|x86
49 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Debug|x86.Deploy.0 = Debug|x86
50 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|Any CPU.ActiveCfg = Release|x64
51 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|Any CPU.Build.0 = Release|x64
52 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|Any CPU.Deploy.0 = Release|x64
53 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|arm64.ActiveCfg = Release|arm64
54 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|arm64.Build.0 = Release|arm64
55 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|arm64.Deploy.0 = Release|arm64
56 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x64.ActiveCfg = Release|x64
57 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x64.Build.0 = Release|x64
58 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x64.Deploy.0 = Release|x64
59 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x86.ActiveCfg = Release|x86
60 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x86.Build.0 = Release|x86
61 | {06336E8A-1942-4F75-A8B0-6720786EA45E}.Release|x86.Deploy.0 = Release|x86
62 | EndGlobalSection
63 | GlobalSection(SolutionProperties) = preSolution
64 | HideSolutionNode = FALSE
65 | EndGlobalSection
66 | GlobalSection(ExtensibilityGlobals) = postSolution
67 | SolutionGuid = {422DCB86-7F61-434B-881F-173F93CA5B25}
68 | EndGlobalSection
69 | EndGlobal
70 |
--------------------------------------------------------------------------------
/WindowExtensions/DisplayInformation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace WinUIExtensions.Desktop
6 | {
7 |
8 | public class DisplayInfo
9 | {
10 | public string Availability { get; set; }
11 | public int ScreenHeight { get; set; }
12 | public int ScreenWidth { get; set; }
13 | public int ScreenEfectiveHeight
14 | {
15 | get
16 | {
17 | int widthDPI;
18 | _ = PInvoke.SHCore.GetDpiForMonitor(hMonitor,
19 | PInvoke.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out widthDPI, out _);
20 | float scalingFactor = (float)widthDPI / 96;
21 | return (int)(ScreenHeight / scalingFactor);
22 | }
23 | }
24 | public int ScreenEfectiveWidth
25 | {
26 | get
27 | {
28 | int heightDPI;
29 | _ = PInvoke.SHCore.GetDpiForMonitor(hMonitor,
30 | PInvoke.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out _, out heightDPI);
31 | float scalingFactor = (float)heightDPI / 96;
32 | return (int)(ScreenWidth / scalingFactor);
33 | }
34 | }
35 | public string DeviceName { get; set; }
36 | public PInvoke.RECT WorkArea { get; set; }
37 | public IntPtr hMonitor { get; set; }
38 | }
39 |
40 | unsafe public class DisplayInformation
41 | {
42 | public static int ConvertEpxToPixel(IntPtr hwnd, int effectivePixels)
43 | {
44 | float scalingFactor = GetScalingFactor(hwnd);
45 | return (int)(effectivePixels * scalingFactor);
46 | }
47 |
48 | public static int ConvertPixelToEpx(IntPtr hwnd, int pixels)
49 | {
50 | float scalingFactor = GetScalingFactor(hwnd);
51 | return (int)(pixels / scalingFactor);
52 | }
53 |
54 | public static float GetScalingFactor(IntPtr hwnd)
55 | {
56 | var dpi = PInvoke.User32.GetDpiForWindow(hwnd);
57 | float scalingFactor = (float)dpi / 96;
58 | return scalingFactor;
59 | }
60 |
61 | public static DisplayInfo GetDisplay(IntPtr hwnd)
62 | {
63 | DisplayInfo di = null;
64 | IntPtr hMonitor;
65 | PInvoke.RECT rc;
66 | PInvoke.User32.GetWindowRect(hwnd, out rc);
67 | hMonitor = PInvoke.User32.MonitorFromRect(ref rc, PInvoke.User32.MonitorOptions.MONITOR_DEFAULTTONEAREST);
68 |
69 | PInvoke.User32.MONITORINFOEX mi = new PInvoke.User32.MONITORINFOEX();
70 | mi.cbSize = Marshal.SizeOf(mi);
71 | bool success = PInvoke.User32.GetMonitorInfo(hMonitor, out mi);
72 | if (success)
73 | {
74 | di = ConvertMonitorInfoToDisplayInfo(hMonitor, mi);
75 | }
76 | return di;
77 | }
78 |
79 | private static DisplayInfo ConvertMonitorInfoToDisplayInfo(IntPtr hMonitor, PInvoke.User32.MONITORINFOEX mi)
80 | {
81 | return new DisplayInfo
82 | {
83 | ScreenWidth = mi.Monitor.right - mi.Monitor.left,
84 | ScreenHeight = mi.Monitor.bottom - mi.Monitor.top,
85 | DeviceName = new string(mi.DeviceName),
86 | WorkArea = mi.WorkArea,
87 | Availability = mi.Flags.ToString(),
88 | hMonitor = hMonitor
89 | };
90 | }
91 |
92 | unsafe public static List GetDisplays()
93 | {
94 | List col = new();
95 |
96 | _ = EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero,
97 | delegate (IntPtr hMonitor, IntPtr hdcMonitor, ref PInvoke.RECT lprcMonitor, IntPtr dwData)
98 | {
99 | PInvoke.User32.MONITORINFOEX mi = new PInvoke.User32.MONITORINFOEX();
100 | mi.cbSize = Marshal.SizeOf(mi);
101 | bool success = PInvoke.User32.GetMonitorInfo(hMonitor, out mi);
102 | if (success)
103 | {
104 | DisplayInfo di = ConvertMonitorInfoToDisplayInfo(hMonitor, mi);
105 | col.Add(di);
106 | }
107 | return true;
108 | }, IntPtr.Zero);
109 | return col;
110 | }
111 |
112 | public enum UserInteractionModeEnum { Touch, Mouse };
113 | public static UserInteractionModeEnum UserInteractionMode
114 | {
115 | get
116 | {
117 | // TODO: Have a counterpart event listeining the message WM_SETTINGCHANGE
118 | UserInteractionModeEnum userInteractionMode = UserInteractionModeEnum.Mouse;
119 | int SM_CONVERTIBLESLATEMODE = 0x2003;
120 | int state = GetSystemMetrics(SM_CONVERTIBLESLATEMODE);//O for tablet
121 | if(state == 0)
122 | {
123 | userInteractionMode = UserInteractionModeEnum.Touch;
124 | }
125 | return userInteractionMode;
126 | }
127 | }
128 |
129 | [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "GetSystemMetrics")]
130 | private static extern int GetSystemMetrics(int nIndex);
131 |
132 | [DllImport("user32.dll")]
133 | static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, EnumMonitorsDelegate lpfnEnum, IntPtr dwData);
134 | delegate bool EnumMonitorsDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref PInvoke.RECT lprcMonitor, IntPtr dwData);
135 |
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Desktop Window
2 | This is just a sample of a .NET 5 APIs that extend the Microsoft.UI.Xaml.Window of WinUI 3 in Reunion 0.5
3 |
4 | > This code is AS IS. It's just for demo proposals
5 |
6 |
7 | XAML code snippet:
8 | ```XML
9 |
10 |
14 |
15 |
16 | ...
17 |
18 |
19 | ```
20 |
21 | Code behind in C#
22 | ```CS
23 |
24 | using Microsoft.UI.Xaml;
25 | using Microsoft.UI.Xaml.Controls;
26 | using System;
27 | using WinUIExtensions.Desktop;
28 |
29 | namespace DesktopWindowSample
30 | {
31 | public sealed partial class MainWindow : DesktopWindow
32 | {
33 | public MainWindow()
34 | {
35 | this.InitializeComponent();
36 |
37 | //DesktopWindow Features
38 |
39 | // Set the Max height and width in effective pixels
40 | this.MaxHeight = 800;
41 | this.MaxWidth = 1024;
42 |
43 | // Set the Min height and width in effective pixels
44 | this.MinHeight = 400;
45 | this.MinWidth = 400;
46 |
47 | // Set the width and Heigh in effective pixels
48 | this.Width = 600;
49 | this.Height = 600;
50 |
51 | // Set the Icon of the window.
52 | this.Icon = "WinUI3.ico";
53 |
54 | // Set the placement of the Window top, left
55 | SetWindowPlacement(0, 0);
56 |
57 | //Fire before closing the window so you can cancel the close event
58 | this.Closing += MainWindow_Closing;
59 |
60 | //Fire when the user moves the window
61 | this.Moving += MainWindow_Moving;
62 | //Fire when the users change the size of the window
63 | this.Sizing += MainWindow_Sizing;
64 | //Fire when the Dpi of the display that host the window changes
65 | this.DpiChanged += MainWindow_DpiChanged;
66 | //Fire when the orientation (portrait and landscape) of the display that host the window changes
67 | this.OrientationChanged += MainWindow_OrientationChanged;
68 |
69 | //Get the heigh and the width
70 | debugTBox.Text = $" Size (Height: { this.Height } Width: { this.Width })";
71 |
72 |
73 | //Get the List of monitors/displays
74 | var list = WinUIExtensions.Desktop.DisplayInformation.GetDisplays();
75 |
76 | foreach (var item in list)
77 | {
78 | systemTBox.Text += $"Display ->" +
79 | $"\n Device Name: {item.DeviceName}" +
80 | $"\n Work Area: ({item.WorkArea.top},{item.WorkArea.left},{item.WorkArea.bottom},{item.WorkArea.right})" +
81 | $"\n ScreenHeight: {item.ScreenHeight}" +
82 | $"\n ScreenWidth:{item.ScreenWidth}" +
83 | $"\n Effective Pixels: width({item.ScreenEfectiveWidth}), height({item.ScreenEfectiveHeight})" +
84 | $"\n Availability {item.Availability}\n\n";
85 | }
86 |
87 | //Get the current DPI of the display that host the window
88 | dpiChangedTBox.Text = $"DPI: {this.Dpi}";
89 | }
90 |
91 | private void MainWindow_OrientationChanged(object sender, WindowOrientationChangedEventArgs e)
92 | {
93 | dpiChangedTBox.Text = $"DPI: {this.Dpi} + Orientation: { e.Orientation.ToString("g")}";
94 | }
95 |
96 | private void MainWindow_DpiChanged(object sender, WindowDpiChangedEventArgs e)
97 | {
98 | dpiChangedTBox.Text = $"DPI Changed:{ e.Dpi} - {this.Dpi} ";
99 | }
100 |
101 | private void MainWindow_Sizing(object sender, WindowSizingEventArgs e)
102 | {
103 | var windowPosition = GetWindowPosition();
104 | debugTBox.Text = $"Height: { this.Height } Width: { this.Width }\n " +
105 | $"Top: {windowPosition.Top} Left:{windowPosition.Left}";
106 | }
107 |
108 | private void MainWindow_Moving(object sender, WindowMovingEventArgs e)
109 | {
110 | debugTBox.Text = $"Height: { this.Height } Width: { this.Width }\n " +
111 | $"Top: {e.NewPosition.Top} Left:{e.NewPosition.Left}";
112 | }
113 |
114 | private async void MainWindow_Closing(object sender, WindowClosingEventArgs e)
115 | {
116 | ContentDialog contentDialog = new ContentDialog();
117 | contentDialog.Content = "Close it?";
118 | contentDialog.XamlRoot = this.Content.XamlRoot;
119 | contentDialog.PrimaryButtonText = "Yes";
120 | contentDialog.CloseButtonText = "No";
121 | contentDialog.IsPrimaryButtonEnabled = true;
122 | var r = await contentDialog.ShowAsync();
123 | if (r == ContentDialogResult.Primary)
124 | {
125 | // Cancel the close event
126 | e.TryCancel();
127 | }
128 | }
129 |
130 | //Center the Window on the display
131 | private void OnCenterClick(object sender, RoutedEventArgs e)
132 | {
133 | SetWindowPlacement(Placement.Center);
134 | }
135 |
136 | //Place the Window on the Top Left
137 | private void OnTopLeft(object sender, RoutedEventArgs e)
138 | {
139 | SetWindowPlacement(Placement.TopLeftCorner);
140 | }
141 |
142 | //Place the Window on the Bottom Left
143 | private void OnBottomLeft(object sender, RoutedEventArgs e)
144 | {
145 | SetWindowPlacement(Placement.BottomLeftCorner);
146 | }
147 |
148 | //Maximize the Window
149 | private void OnMaximize(object sender, RoutedEventArgs e)
150 | {
151 | Maximize();
152 | }
153 |
154 | //Minimize the Window
155 | private void OnMinimize(object sender, RoutedEventArgs e)
156 | {
157 | Minimize();
158 | }
159 |
160 | //Restore the Window
161 | private void OnRestore(object sender, RoutedEventArgs e)
162 | {
163 | Restore();
164 | }
165 |
166 | //Bring the Window to the top
167 | private void OnBringToTop(object sender, RoutedEventArgs e)
168 | {
169 | BringToTop();
170 | }
171 |
172 | private void OnClosingApplication(object sender, RoutedEventArgs e)
173 | {
174 | Application.Current.Exit();
175 | }
176 | }
177 | }
178 | ```
179 |
--------------------------------------------------------------------------------
/DesktopWindowDemo/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.UI.Xaml;
2 | using Microsoft.UI.Xaml.Controls;
3 | using System;
4 | using WinUIExtensions.Desktop;
5 |
6 | namespace DesktopWindowDemo
7 | {
8 | ///
9 | /// An empty window that can be used on its own or navigated to within a Frame.
10 | ///
11 | public sealed partial class MainWindow : DesktopWindow
12 | {
13 | public MainWindow()
14 | {
15 | this.InitializeComponent();
16 | // MUX.Window features
17 | this.Title = "Showcase DesktopWindow API";
18 | //this.ExtendsContentIntoTitleBar = true;
19 | //SetTitleBar(myTitleBar);
20 |
21 | //DesktopWindow Features
22 |
23 | // Set the Max height and width in effective pixels
24 | this.MaxHeight = 800;
25 | this.MaxWidth = 1024;
26 |
27 | // Set the Min height and width in effective pixels
28 | this.MinHeight = 400;
29 | this.MinWidth = 400;
30 |
31 | // Set the width and Heigh in effective pixels
32 | this.Width = 600;
33 | this.Height = 600;
34 |
35 | //Fire when the OS Setting Preferred Language Changes.
36 | this.PreferredLanguageChanged += MainWindow_LanguageChanged;
37 | preferredLanguageTBox.Text = $"PreferredLanguageChanged {Windows.System.UserProfile.GlobalizationPreferences.Languages[0]}";
38 |
39 | // Set the Icon of the window.
40 | this.Icon = "Assets/WinUI3.ico";
41 |
42 | // Set the placement of the Window top, left
43 | SetWindowPlacement(0, 0);
44 |
45 | //Fire before closing the window so you can cancel the close event
46 | this.Closing += MainWindow_Closing;
47 |
48 | //Fire when the user moves the window
49 | this.Moving += MainWindow_Moving;
50 | //Fire when the users change the size of the window
51 | this.Sizing += MainWindow_Sizing;
52 | //Fire when the Dpi of the display that host the window changes
53 | this.DpiChanged += MainWindow_DpiChanged;
54 | //Fire when the orientation (portrait and landscape) of the display that host the window changes
55 | this.OrientationChanged += MainWindow_OrientationChanged;
56 |
57 | //Get the heigh and the width
58 | debugTBox.Text = $" Size (Height: {this.Height} Width: {this.Width})";
59 |
60 |
61 | //Get the List of monitors/displays
62 | var list = WinUIExtensions.Desktop.DisplayInformation.GetDisplays();
63 |
64 | foreach (var item in list)
65 | {
66 | systemTBox.Text += $"Display ->" +
67 | $"\n Device Name: {item.DeviceName}" +
68 | $"\n Work Area: ({item.WorkArea.top},{item.WorkArea.left},{item.WorkArea.bottom},{item.WorkArea.right})" +
69 | $"\n ScreenHeight: {item.ScreenHeight}" +
70 | $"\n ScreenWidth:{item.ScreenWidth}" +
71 | $"\n Effective Pixels: width({item.ScreenEfectiveWidth}), height({item.ScreenEfectiveHeight})" +
72 | $"\n Availability {item.Availability}\n\n";
73 | }
74 |
75 | //Get the current DPI of the display that host the window
76 | dpiChangedTBox.Text = $"DPI: {this.Dpi}";
77 | }
78 |
79 | private void MainWindow_LanguageChanged(object sender, WindowPreferredLanguageChangedEventArgs e)
80 | {
81 | preferredLanguageTBox.Text = $"Preferred Language: Old Language: {e.OldLanguage } Current Language {e.NewLanguage}";
82 | }
83 |
84 | private void MainWindow_OrientationChanged(object sender, WindowOrientationChangedEventArgs e)
85 | {
86 | dpiChangedTBox.Text = $"DPI: {this.Dpi} + Orientation: {e.Orientation.ToString("g")}";
87 | }
88 |
89 | private void MainWindow_DpiChanged(object sender, WindowDpiChangedEventArgs e)
90 | {
91 | dpiChangedTBox.Text = $"DPI Changed:{e.Dpi} - {this.Dpi} ";
92 | }
93 |
94 | private void MainWindow_Sizing(object sender, WindowSizingEventArgs e)
95 | {
96 | var windowPosition = GetWindowPosition();
97 | debugTBox.Text = $"Height: {this.Height} Width: {this.Width}\n " +
98 | $"Top: {windowPosition.Top} Left:{windowPosition.Left}";
99 | }
100 |
101 | private void MainWindow_Moving(object sender, WindowMovingEventArgs e)
102 | {
103 | debugTBox.Text = $"Height: {this.Height} Width: {this.Width}\n " +
104 | $"Top: {e.NewPosition.Top} Left:{e.NewPosition.Left}";
105 | }
106 |
107 | private async void MainWindow_Closing(object sender, WindowClosingEventArgs e)
108 | {
109 | ContentDialog contentDialog = new ContentDialog();
110 | contentDialog.Content = "Close it?";
111 | contentDialog.XamlRoot = this.Content.XamlRoot;
112 | contentDialog.PrimaryButtonText = "Yes";
113 | contentDialog.CloseButtonText = "No";
114 | contentDialog.IsPrimaryButtonEnabled = true;
115 | var r = await contentDialog.ShowAsync();
116 | if (r == ContentDialogResult.Primary)
117 | {
118 | // Cancel the close event
119 | e.TryCancel();
120 | }
121 | }
122 |
123 | //Center the Window on the display
124 | private void OnCenterClick(object sender, RoutedEventArgs e)
125 | {
126 | SetWindowPlacement(Placement.Center);
127 | }
128 |
129 | //Place the Window on the Top Left
130 | private void OnTopLeft(object sender, RoutedEventArgs e)
131 | {
132 | SetWindowPlacement(Placement.TopLeftCorner);
133 | }
134 |
135 | //Place the Window on the Bottom Left
136 | private void OnBottomLeft(object sender, RoutedEventArgs e)
137 | {
138 | SetWindowPlacement(Placement.BottomLeftCorner);
139 | }
140 |
141 | //Maximize the Window
142 | private void OnMaximize(object sender, RoutedEventArgs e)
143 | {
144 | Maximize();
145 | }
146 |
147 | //Minimize the Window
148 | private void OnMinimize(object sender, RoutedEventArgs e)
149 | {
150 | Minimize();
151 | }
152 |
153 | //Restore the Window
154 | private void OnRestore(object sender, RoutedEventArgs e)
155 | {
156 | Restore();
157 | }
158 |
159 | //Bring the Window to the top
160 | private void OnBringToTop(object sender, RoutedEventArgs e)
161 | {
162 | BringToTop();
163 | }
164 |
165 | private void OnClosingApplication(object sender, RoutedEventArgs e)
166 | {
167 | Application.Current.Exit();
168 | }
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/WindowExtensions/DesktopWindow.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.UI.Xaml;
2 |
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | using WinRT;
7 |
8 | namespace WinUIExtensions.Desktop
9 | {
10 | public class WindowPosition
11 | {
12 | public int Top { get; private set; }
13 | public int Left { get; private set; }
14 | public WindowPosition(int top, int left)
15 | {
16 | this.Top = top;
17 | this.Left = left;
18 | }
19 | }
20 |
21 | public class WindowSizingEventArgs : EventArgs
22 | {
23 | public DesktopWindow Window { get; private set; }
24 | public WindowSizingEventArgs(DesktopWindow window)
25 | {
26 | Window = window;
27 | }
28 | }
29 |
30 | public class WindowClosingEventArgs : EventArgs
31 | {
32 | public DesktopWindow Window { get; private set; }
33 | public WindowClosingEventArgs(DesktopWindow window)
34 | {
35 | Window = window;
36 | }
37 |
38 | public void TryCancel()
39 | {
40 | Window.IsClosing = true;
41 | Window.Close();
42 | }
43 | }
44 |
45 | public class WindowPreferredLanguageChangedEventArgs : EventArgs
46 | {
47 | public DesktopWindow Window { get; private set; }
48 | public string OldLanguage { get; private set; }
49 | public string NewLanguage { get; private set; }
50 |
51 | public WindowPreferredLanguageChangedEventArgs(DesktopWindow window, string oldLanguage, string newLanguage)
52 | {
53 | Window = window;
54 | OldLanguage = oldLanguage;
55 | NewLanguage = newLanguage;
56 | }
57 | }
58 |
59 | public class WindowDpiChangedEventArgs : EventArgs
60 | {
61 | public DesktopWindow Window { get; private set; }
62 | public int Dpi { get; private set; }
63 |
64 | public WindowDpiChangedEventArgs(DesktopWindow window, int newDpi)
65 | {
66 | Window = window;
67 | Dpi = newDpi;
68 | }
69 | }
70 |
71 | public class WindowOrientationChangedEventArgs : EventArgs
72 | {
73 | public DesktopWindow Window { get; private set; }
74 | public DesktopWindow.Orientation Orientation { get; private set; }
75 |
76 | public WindowOrientationChangedEventArgs(DesktopWindow window, DesktopWindow.Orientation newOrientationi)
77 | {
78 | Window = window;
79 | Orientation = newOrientationi;
80 | }
81 | }
82 |
83 | public class WindowMovingEventArgs : EventArgs
84 | {
85 | public DesktopWindow Window { get; private set; }
86 | public WindowPosition NewPosition { get; private set; }
87 | public int Top { get; private set; }
88 | public int Left { get; private set; }
89 | public WindowMovingEventArgs(DesktopWindow window, WindowPosition windowPosition)
90 | {
91 | Window = window;
92 | NewPosition = new(windowPosition.Top, windowPosition.Left);
93 | }
94 | }
95 |
96 | public class WindowKeyDownEventArgs : EventArgs
97 | {
98 | public DesktopWindow Window { get; private set; }
99 | public int Key { get; private set; }
100 |
101 | public WindowKeyDownEventArgs(DesktopWindow window, int key)
102 | {
103 | Window = window;
104 | Key = key;
105 | }
106 | }
107 |
108 | public class DesktopWindow : Window
109 | {
110 | public enum Orientation { Landscape, Portrait }
111 | public enum Placement { Center, TopLeftCorner, BottomLeftCorner } //Future: align to the top corner, etc..
112 | public int Width
113 | {
114 | get
115 | {
116 | return DisplayInformation.ConvertPixelToEpx(_hwnd, GetWidthWin32(_hwnd));
117 | }
118 | set
119 | {
120 | SetWindowWidthWin32(_hwnd, DisplayInformation.ConvertEpxToPixel(_hwnd, value));
121 | }
122 | }
123 |
124 | public int Height
125 | {
126 | get
127 | {
128 | return DisplayInformation.ConvertPixelToEpx(_hwnd, GetHeightWin32(_hwnd));
129 | }
130 | set
131 | {
132 | SetWindowHeightWin32(_hwnd, DisplayInformation.ConvertEpxToPixel(_hwnd, value));
133 | }
134 | }
135 |
136 | public int MinWidth { get; set; } = -1;
137 | public int MinHeight { get; set; } = -1;
138 | public int MaxWidth { get; set; } = -1;
139 | public int MaxHeight { get; set; } = -1;
140 |
141 | public bool IsClosing { get; set; }
142 |
143 | public event EventHandler Closing;
144 | public event EventHandler PreferredLanguageChanged;
145 | public event EventHandler Moving;
146 | public event EventHandler Sizing;
147 | public event EventHandler DpiChanged;
148 | public event EventHandler OrientationChanged;
149 | public event EventHandler KeyDown;
150 |
151 | private string _preferredLanguage;
152 |
153 | public IntPtr Hwnd
154 | {
155 | get { return _hwnd; }
156 | }
157 |
158 | public int Dpi
159 | {
160 | get { return PInvoke.User32.GetDpiForWindow(_hwnd); }
161 | }
162 |
163 | public DesktopWindow()
164 | {
165 | SubClassingWin32();
166 | _currentOrientation = GetWindowOrientationWin32(_hwnd);
167 | _preferredLanguage = Windows.System.UserProfile.GlobalizationPreferences.Languages[0];
168 | }
169 |
170 | public void SetWindowPlacement(Placement placement)
171 | {
172 | switch (placement)
173 | {
174 | case Placement.Center:
175 | PlacementCenterWindowInMonitorWin32(_hwnd);
176 | break;
177 | case Placement.TopLeftCorner:
178 | PlacementTopLefWindowInMonitorWin32(_hwnd);
179 | break;
180 | case Placement.BottomLeftCorner:
181 | PlacementBottomLefWindowInMonitorWin32(_hwnd);
182 | break;
183 | }
184 | }
185 |
186 | public void SetWindowPlacement(int topExp, int leftExp)
187 | {
188 | SetWindowPlacementWin32(_hwnd, DisplayInformation.ConvertEpxToPixel(_hwnd, topExp),
189 | DisplayInformation.ConvertEpxToPixel(_hwnd, leftExp));
190 | }
191 |
192 | public WindowPosition GetWindowPosition()
193 | {
194 | //windowPosition comes in pixels(Win32), so you need to convert into epx
195 | WindowPosition windowPosition = GetWindowPositionWin32(_hwnd);
196 |
197 | return new(DisplayInformation.ConvertPixelToEpx(_hwnd, windowPosition.Top),
198 | DisplayInformation.ConvertPixelToEpx(_hwnd, windowPosition.Left));
199 | }
200 |
201 | public string Icon
202 | {
203 | get { return _iconResource; }
204 | set
205 | {
206 | _iconResource = value;
207 | LoadIcon(_hwnd, _iconResource);
208 | }
209 | }
210 |
211 | public void Maximize()
212 | {
213 | _ = PInvoke.User32.ShowWindow(_hwnd, PInvoke.User32.WindowShowStyle.SW_MAXIMIZE);
214 | }
215 |
216 | public void Minimize()
217 | {
218 | _ = PInvoke.User32.ShowWindow(_hwnd, PInvoke.User32.WindowShowStyle.SW_MINIMIZE);
219 | }
220 |
221 | public void Restore()
222 | {
223 | _ = PInvoke.User32.ShowWindow(_hwnd, PInvoke.User32.WindowShowStyle.SW_RESTORE);
224 | }
225 |
226 | public void Hide()
227 | {
228 | _ = PInvoke.User32.ShowWindow(_hwnd, PInvoke.User32.WindowShowStyle.SW_HIDE);
229 | }
230 |
231 | public void BringToTop()
232 | {
233 | _ = PInvoke.User32.SetWindowPos(_hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOPMOST, 0, 0, 0, 0,
234 | PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE | PInvoke.User32.SetWindowPosFlags.SWP_NOSIZE);
235 | }
236 |
237 |
238 | #region Private
239 | private string _iconResource;
240 | private IntPtr _hwnd = IntPtr.Zero;
241 | Orientation _currentOrientation;
242 |
243 | private void OnClosing()
244 | {
245 | WindowClosingEventArgs windowClosingEventArgs = new(this);
246 | Closing.Invoke(this, windowClosingEventArgs);
247 | }
248 |
249 | private void OnWindowLanguageChanged(string oldLanguage, string newLanguage)
250 | {
251 | WindowPreferredLanguageChangedEventArgs eventArgs = new(this, oldLanguage, newLanguage);
252 | PreferredLanguageChanged.Invoke(this, eventArgs);
253 | }
254 |
255 | private void OnWindowMoving()
256 | {
257 | var windowPosition = GetWindowPositionWin32(_hwnd);
258 | //windowPosition comes in pixels(Win32), so you need to convert into epx
259 | WindowMovingEventArgs windowMovingEventArgs = new(this,
260 | new WindowPosition(
261 | DisplayInformation.ConvertPixelToEpx(_hwnd, windowPosition.Top),
262 | DisplayInformation.ConvertPixelToEpx(_hwnd, windowPosition.Left)));
263 | Moving.Invoke(this, windowMovingEventArgs);
264 | }
265 | private void OnWindowSizing()
266 | {
267 | WindowSizingEventArgs windowSizingEventArgs = new(this);
268 | Sizing.Invoke(this, windowSizingEventArgs);
269 | }
270 |
271 | private void OnWindowDpiChanged(int newDpi)
272 | {
273 | WindowDpiChangedEventArgs windowDpiChangedEvent = new(this, newDpi);
274 | DpiChanged.Invoke(this, windowDpiChangedEvent);
275 | }
276 |
277 | private void OnWindowOrientationChanged(Orientation newOrinetation)
278 | {
279 | WindowOrientationChangedEventArgs windowOrientationChangedEventArgs = new(this, newOrinetation);
280 | OrientationChanged.Invoke(this, windowOrientationChangedEventArgs);
281 | }
282 |
283 | private void OnWindowKeyDown(int key)
284 | {
285 | WindowKeyDownEventArgs windowKeyDownEventArgs = new(this, key);
286 | KeyDown.Invoke(this, windowKeyDownEventArgs);
287 | }
288 |
289 | private delegate IntPtr WinProc(IntPtr hWnd, PInvoke.User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam);
290 | private WinProc newWndProc = null;
291 | private IntPtr oldWndProc = IntPtr.Zero;
292 | [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
293 | private static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, PInvoke.User32.WindowLongIndexFlags nIndex, WinProc newProc);
294 | [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]
295 | private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, PInvoke.User32.WindowLongIndexFlags nIndex, WinProc newProc);
296 | // This static method is required because Win32 does not support
297 | // GetWindowLongPtr directly
298 | private static IntPtr SetWindowLongPtr(IntPtr hWnd, PInvoke.User32.WindowLongIndexFlags nIndex, WinProc newProc)
299 | {
300 | if (IntPtr.Size == 8)
301 | return SetWindowLongPtr64(hWnd, nIndex, newProc);
302 | else
303 | return SetWindowLongPtr32(hWnd, nIndex, newProc);
304 | }
305 | [DllImport("user32.dll")]
306 | static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, PInvoke.User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam);
307 |
308 | private void SubClassingWin32()
309 | {
310 | //Get the Window's HWND
311 | _hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
312 | if (_hwnd == IntPtr.Zero)
313 | {
314 | throw new NullReferenceException("The Window Handle is null.");
315 |
316 | }
317 | newWndProc = new WinProc(NewWindowProc);
318 | oldWndProc = SetWindowLongPtr(_hwnd, PInvoke.User32.WindowLongIndexFlags.GWL_WNDPROC, newWndProc);
319 | }
320 |
321 | private void LoadIcon(IntPtr hwnd, string iconName)
322 | {
323 | const int ICON_SMALL = 0;
324 | const int ICON_BIG = 1;
325 |
326 | var hSmallIcon = PInvoke.User32.LoadImage(
327 | IntPtr.Zero,
328 | iconName,
329 | PInvoke.User32.ImageType.IMAGE_ICON,
330 | PInvoke.User32.GetSystemMetrics(PInvoke.User32.SystemMetric.SM_CXSMICON),
331 | PInvoke.User32.GetSystemMetrics(PInvoke.User32.SystemMetric.SM_CYSMICON),
332 | PInvoke.User32.LoadImageFlags.LR_LOADFROMFILE);
333 |
334 | PInvoke.User32.SendMessage(hwnd, PInvoke.User32.WindowMessage.WM_SETICON, (IntPtr)ICON_SMALL, hSmallIcon);
335 |
336 | var hBigIcon = PInvoke.User32.LoadImage(
337 | IntPtr.Zero,
338 | iconName,
339 | PInvoke.User32.ImageType.IMAGE_ICON,
340 | PInvoke.User32.GetSystemMetrics(PInvoke.User32.SystemMetric.SM_CXICON),
341 | PInvoke.User32.GetSystemMetrics(PInvoke.User32.SystemMetric.SM_CYICON),
342 | PInvoke.User32.LoadImageFlags.LR_LOADFROMFILE);
343 |
344 | PInvoke.User32.SendMessage(hwnd, PInvoke.User32.WindowMessage.WM_SETICON, (IntPtr)ICON_BIG, hBigIcon);
345 | }
346 |
347 | [StructLayout(LayoutKind.Sequential)]
348 | private struct MINMAXINFO
349 | {
350 | public PInvoke.POINT ptReserved;
351 | public PInvoke.POINT ptMaxSize;
352 | public PInvoke.POINT ptMaxPosition;
353 | public PInvoke.POINT ptMinTrackSize;
354 | public PInvoke.POINT ptMaxTrackSize;
355 | }
356 |
357 | private IntPtr NewWindowProc(IntPtr hWnd, PInvoke.User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam)
358 | {
359 | switch (Msg)
360 | {
361 | case PInvoke.User32.WindowMessage.WM_GETMINMAXINFO:
362 | MINMAXINFO minMaxInfo = Marshal.PtrToStructure(lParam);
363 | if (MinWidth >= 0) minMaxInfo.ptMinTrackSize.x = DisplayInformation.ConvertEpxToPixel(hWnd, MinWidth);
364 | if (MinHeight >= 0) minMaxInfo.ptMinTrackSize.y = DisplayInformation.ConvertEpxToPixel(hWnd, MinHeight);
365 | if (MaxWidth > 0) minMaxInfo.ptMaxTrackSize.x = DisplayInformation.ConvertEpxToPixel(hWnd, MaxWidth);
366 | if (MaxHeight > 0) minMaxInfo.ptMaxTrackSize.y = DisplayInformation.ConvertEpxToPixel(hWnd, MaxHeight);
367 | Marshal.StructureToPtr(minMaxInfo, lParam, true);
368 | break;
369 |
370 | case PInvoke.User32.WindowMessage.WM_SETTINGCHANGE:
371 | var newLanguage = Windows.System.UserProfile.GlobalizationPreferences.Languages[0];
372 | if (_preferredLanguage != newLanguage)
373 | {
374 | OnWindowLanguageChanged(_preferredLanguage, newLanguage);
375 | _preferredLanguage = newLanguage;
376 | }
377 | break;
378 |
379 | case PInvoke.User32.WindowMessage.WM_CLOSE:
380 |
381 | //If there is a Closing event handler and the close message wasn't send via
382 | //this event (that set IsClosing=true), the message is ignored.
383 | if (this.Closing is not null)
384 | {
385 | if (IsClosing == false)
386 | {
387 | OnClosing();
388 | }
389 | return IntPtr.Zero;
390 | }
391 | break;
392 |
393 | case PInvoke.User32.WindowMessage.WM_MOVE:
394 | if (this.Moving is not null)
395 | {
396 | OnWindowMoving();
397 | }
398 | break;
399 | case PInvoke.User32.WindowMessage.WM_SIZING:
400 | if (this.Sizing is not null)
401 | {
402 | OnWindowSizing();
403 | }
404 | break;
405 | case PInvoke.User32.WindowMessage.WM_DPICHANGED:
406 | if (this.DpiChanged is not null)
407 | {
408 | uint dpi = HiWord(wParam);
409 | OnWindowDpiChanged((int)dpi);
410 | }
411 | break;
412 | case PInvoke.User32.WindowMessage.WM_DISPLAYCHANGE:
413 | if (this.OrientationChanged is not null)
414 | {
415 | var newOrinetation = GetWindowOrientationWin32(hWnd);
416 | if (newOrinetation != _currentOrientation)
417 | {
418 | _currentOrientation = newOrinetation;
419 | OnWindowOrientationChanged(newOrinetation);
420 | }
421 | }
422 | break;
423 | //This don't work.
424 | case PInvoke.User32.WindowMessage.WM_KEYDOWN:
425 | if (this.KeyDown is not null)
426 | {
427 | int value = (int)wParam;
428 | OnWindowKeyDown(value);
429 | }
430 | break;
431 | }
432 | return CallWindowProc(oldWndProc, hWnd, Msg, wParam, lParam);
433 | }
434 |
435 | private Orientation GetWindowOrientationWin32(IntPtr hwnd)
436 | {
437 | Orientation orientationEnum;
438 | int theScreenWidth = DisplayInformation.GetDisplay(hwnd).ScreenWidth;
439 | int theScreenHeight = DisplayInformation.GetDisplay(hwnd).ScreenHeight;
440 | if (theScreenWidth > theScreenHeight)
441 | orientationEnum = Orientation.Landscape;
442 | else
443 | orientationEnum = Orientation.Portrait;
444 | return orientationEnum;
445 | }
446 |
447 | private static uint HiWord(IntPtr ptr)
448 | {
449 | uint value = (uint)(int)ptr;
450 | if ((value & 0x80000000) == 0x80000000)
451 | return (value >> 16);
452 | else
453 | return (value >> 16) & 0xffff;
454 | }
455 |
456 | private int GetWidthWin32(IntPtr hwnd)
457 | {
458 | //Get the width
459 | PInvoke.RECT rc;
460 | PInvoke.User32.GetWindowRect(hwnd, out rc);
461 | return rc.right - rc.left;
462 | }
463 |
464 | private int GetHeightWin32(IntPtr hwnd)
465 | {
466 | //Get the width
467 | PInvoke.RECT rc;
468 | PInvoke.User32.GetWindowRect(hwnd, out rc);
469 | return rc.bottom - rc.top;
470 | }
471 |
472 | private void SetWindowSizeWin32(IntPtr hwnd, int width, int height)
473 | {
474 | PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
475 | 0, 0, width, height,
476 | PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE |
477 | PInvoke.User32.SetWindowPosFlags.SWP_NOACTIVATE);
478 | }
479 |
480 | private WindowPosition GetWindowPositionWin32(IntPtr hwnd)
481 | {
482 | PInvoke.RECT rc;
483 | PInvoke.User32.GetWindowRect(hwnd, out rc);
484 | return new WindowPosition(rc.top, rc.left);
485 | }
486 |
487 | private void SetWindowWidthWin32(IntPtr hwnd, int width)
488 | {
489 | int currentHeightInPixels = GetHeightWin32(hwnd);
490 |
491 | PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
492 | 0, 0, width, currentHeightInPixels,
493 | PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE |
494 | PInvoke.User32.SetWindowPosFlags.SWP_NOACTIVATE);
495 | }
496 |
497 | private void SetWindowHeightWin32(IntPtr hwnd, int height)
498 | {
499 | int currentWidthInPixels = GetWidthWin32(hwnd);
500 |
501 | PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
502 | 0, 0, currentWidthInPixels, height,
503 | PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE |
504 | PInvoke.User32.SetWindowPosFlags.SWP_NOACTIVATE);
505 | }
506 |
507 | private void PlacementTopLefWindowInMonitorWin32(IntPtr hwnd)
508 | {
509 | var displayInfo = DisplayInformation.GetDisplay(hwnd);
510 | SetWindowPlacementWin32(hwnd, displayInfo.WorkArea.top, displayInfo.WorkArea.left);
511 | }
512 | private void PlacementBottomLefWindowInMonitorWin32(IntPtr hwnd)
513 | {
514 | var displayInfo = DisplayInformation.GetDisplay(hwnd);
515 | SetWindowPlacementWin32(hwnd, displayInfo.WorkArea.bottom - GetHeightWin32(_hwnd), displayInfo.WorkArea.left);
516 | }
517 |
518 |
519 | private void SetWindowPlacementWin32(IntPtr hwnd, int top, int left)
520 | {
521 | PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
522 | left, top, 0, 0,
523 | PInvoke.User32.SetWindowPosFlags.SWP_NOSIZE |
524 | PInvoke.User32.SetWindowPosFlags.SWP_NOZORDER |
525 | PInvoke.User32.SetWindowPosFlags.SWP_NOACTIVATE);
526 | }
527 |
528 | private void PlacementCenterWindowInMonitorWin32(IntPtr hwnd)
529 | {
530 | PInvoke.RECT rc;
531 | PInvoke.User32.GetWindowRect(hwnd, out rc);
532 | ClipOrCenterRectToMonitorWin32(ref rc, true, true);
533 | PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
534 | rc.left, rc.top, 0, 0,
535 | PInvoke.User32.SetWindowPosFlags.SWP_NOSIZE |
536 | PInvoke.User32.SetWindowPosFlags.SWP_NOZORDER |
537 | PInvoke.User32.SetWindowPosFlags.SWP_NOACTIVATE);
538 | }
539 |
540 | private void ClipOrCenterRectToMonitorWin32(ref PInvoke.RECT prc, bool UseWorkArea, bool IsCenter)
541 | {
542 | IntPtr hMonitor;
543 | PInvoke.RECT rc;
544 | int w = prc.right - prc.left;
545 | int h = prc.bottom - prc.top;
546 |
547 | hMonitor = PInvoke.User32.MonitorFromRect(ref prc, PInvoke.User32.MonitorOptions.MONITOR_DEFAULTTONEAREST);
548 |
549 | PInvoke.User32.MONITORINFO mi = new PInvoke.User32.MONITORINFO();
550 | mi.cbSize = Marshal.SizeOf(mi);
551 |
552 | PInvoke.User32.GetMonitorInfo(hMonitor, ref mi);
553 |
554 | rc = UseWorkArea ? mi.rcWork : mi.rcMonitor;
555 |
556 | if (IsCenter)
557 | {
558 | prc.left = rc.left + (rc.right - rc.left - w) / 2;
559 | prc.top = rc.top + (rc.bottom - rc.top - h) / 2;
560 | prc.right = prc.left + w;
561 | prc.bottom = prc.top + h;
562 | }
563 | else
564 | {
565 | prc.left = Math.Max(rc.left, Math.Min(rc.right - w, prc.left));
566 | prc.top = Math.Max(rc.top, Math.Min(rc.bottom - h, prc.top));
567 | prc.right = prc.left + w;
568 | prc.bottom = prc.top + h;
569 | }
570 | }
571 |
572 | #endregion
573 | }
574 | }
575 |
--------------------------------------------------------------------------------