├── .gitattributes ├── .gitignore ├── Directory.Build.props ├── LICENSE ├── Microsoft.UI.Xaml.Markup ├── Microsoft.UI.Xaml.Markup.csproj ├── ReflectionHelperException.cs ├── ReflectionXamlMetadataProvider.cs ├── TypeExtensions.cs ├── XamlReflectionMember.cs └── XamlReflectionType.cs ├── README.md ├── ShortDev.Uwp.Compose ├── App.cs ├── Bindings │ └── RefValue.cs ├── ComposerExtensions.cs ├── Package.appxmanifest ├── Program.cs ├── Properties │ └── launchSettings.json ├── ShortDev.Uwp.Compose.csproj ├── Utils.cs └── app.manifest ├── ShortDev.Uwp.FullTrust.sln ├── ShortDev.Uwp.FullTrust ├── Activation │ └── Win32LaunchActivationArgs.cs ├── Core │ ├── CoreWindowExtensions.cs │ └── CoreWindowFactory.cs ├── GlobalUsings.cs ├── Internal │ └── XamlSynchronizationContext.cs ├── InteropHelper.cs ├── NativeMethods.json ├── NativeMethods.txt ├── ShortDev.Uwp.FullTrust.csproj ├── Xaml │ ├── FullTrustApplication.cs │ ├── XamlWindowConfig.cs │ ├── XamlWindowExtensions.cs │ └── XamlWindowFactory.cs └── readme.txt ├── ShortDev.Uwp.Internal ├── .gitignore ├── Extensions.cs ├── ShortDev.Uwp.Internal.csproj └── idl │ ├── Internal.Windows.ApplicationModel.Core.idl │ ├── Internal.Windows.UI.Core.idl │ ├── Internal.Windows.UI.WindowManagement.idl │ ├── Internal.Windows.UI.Xaml.Hosting.idl │ └── Internal.Windows.UI.Xaml.idl ├── ShortDev.Uwp.Node ├── App.xaml ├── GlobalUsings.cs ├── Initializer.cs ├── ShortDev.Uwp.Node.csproj ├── WinUIApp.cs └── XamlHelper.cs └── ShortDev.Win32 ├── Composition ├── DwmApi.cs └── WindowCompositionHelper.cs ├── GlobalUsings.cs ├── NativeMethods.json ├── NativeMethods.txt ├── ShortDev.Win32.csproj └── Windowing ├── Window.cs ├── WindowCloseRequestedEventArgs.cs └── WindowSubclass.cs /.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 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | preview 4 | enable 5 | enable 6 | 7 | 8 | 9 | true 10 | true 11 | false 12 | 13 | 14 | 15 | x86;x64;arm64 16 | win-x86;win-x64;win-arm64 17 | 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 ShortDevelopment 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/Microsoft.UI.Xaml.Markup.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0-windows10.0.22621.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/ReflectionHelperException.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.UI.Xaml.Markup; 2 | 3 | internal sealed class ReflectionHelperException(string message) : Exception(message) { } 4 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/ReflectionXamlMetadataProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Reflection; 3 | using System.Text; 4 | using Windows.UI.Xaml; 5 | using Windows.UI.Xaml.Markup; 6 | 7 | namespace Microsoft.UI.Xaml.Markup; 8 | 9 | public sealed partial class ReflectionXamlMetadataProvider : IXamlMetadataProvider 10 | { 11 | public ReflectionXamlMetadataProvider() 12 | { 13 | _providers.Add(new(this)); 14 | } 15 | 16 | public IXamlType? GetXamlType(Type type) 17 | => GetXamlTypeInternal(type); 18 | 19 | public IXamlType? GetXamlType(string fullName) 20 | => GetXamlTypeInternal(fullName); 21 | 22 | public XmlnsDefinition[] GetXmlnsDefinitions() 23 | => []; 24 | 25 | internal static IXamlType? GetXamlTypeInternal(Type typeID) 26 | { 27 | if (_xamlTypeCacheByType.TryGetValue(typeID, out var xamlType)) 28 | return xamlType; 29 | 30 | xamlType = CreateXamlType(typeID); 31 | if (xamlType != null) 32 | { 33 | _xamlTypeCacheByName.TryAdd(xamlType.FullName, xamlType); 34 | _xamlTypeCacheByType.TryAdd(xamlType.UnderlyingType, xamlType); 35 | } 36 | return xamlType; 37 | } 38 | 39 | internal static IXamlType? GetXamlTypeInternal(string typeName) 40 | { 41 | string compilerTypeName = TypeExtensions.MakeCompilerTypeName(typeName); 42 | if (string.IsNullOrEmpty(compilerTypeName)) 43 | return null; 44 | 45 | if (_xamlTypeCacheByName.TryGetValue(compilerTypeName, out var xamlType)) 46 | return xamlType; 47 | 48 | xamlType = CreateXamlType(compilerTypeName); 49 | if (xamlType != null) 50 | { 51 | _xamlTypeCacheByName.TryAdd(xamlType.FullName, xamlType); 52 | _xamlTypeCacheByType.TryAdd(xamlType.UnderlyingType, xamlType); 53 | if (!xamlType.FullName.Equals(compilerTypeName)) 54 | throw new ReflectionHelperException($"Created Xaml type '{xamlType.FullName}' has a different name than requested type '{compilerTypeName}'"); 55 | } 56 | return xamlType; 57 | } 58 | 59 | private static IXamlType CreateXamlType(Type typeID) 60 | => XamlReflectionType.Create(typeID); 61 | 62 | private static IXamlType? CreateXamlType(string typeName) 63 | { 64 | string compilerTypeName = TypeExtensions.MakeCompilerTypeName(typeName); 65 | if (IsGenericTypeName(compilerTypeName)) 66 | return ConstructGenericType(compilerTypeName); 67 | return XamlReflectionType.Create(GetNonGenericType(compilerTypeName)); 68 | } 69 | 70 | private static Type? GetNonGenericType(string compilerTypeName) 71 | { 72 | compilerTypeName = TypeExtensions.GetCSharpTypeName(compilerTypeName); 73 | foreach (string assemblyName in _assemblies) 74 | { 75 | try 76 | { 77 | var type = Type.GetType($"{compilerTypeName}, {assemblyName}"); 78 | if (type != null) 79 | return type; 80 | } 81 | catch { } 82 | } 83 | return null; 84 | } 85 | 86 | private static IXamlType? ConstructGenericType(string compilerTypeName) 87 | { 88 | StringBuilder stringBuilder = new(); 89 | Stack> stack = new(); 90 | Stack stack2 = new(); 91 | int i = 0; 92 | while (i < compilerTypeName.Length) 93 | { 94 | char c = compilerTypeName[i]; 95 | if (c <= ',') 96 | { 97 | if (c != ' ') 98 | { 99 | if (c != ',') 100 | { 101 | goto IL_140; 102 | } 103 | if (stringBuilder.Length > 0) 104 | { 105 | string compilerTypeName2 = stringBuilder.ToString(); 106 | stringBuilder.Clear(); 107 | var nonGenericType = GetNonGenericType(compilerTypeName2); 108 | if (nonGenericType == null) 109 | return null; 110 | 111 | stack.Peek().Add(nonGenericType); 112 | } 113 | } 114 | } 115 | else if (c != '<') 116 | { 117 | if (c != '>') 118 | { 119 | goto IL_140; 120 | } 121 | if (stringBuilder.Length > 0) 122 | { 123 | string compilerTypeName3 = stringBuilder.ToString(); 124 | stringBuilder.Clear(); 125 | Type nonGenericType2 = GetNonGenericType(compilerTypeName3); 126 | if (nonGenericType2 == null) 127 | { 128 | return null; 129 | } 130 | stack.Peek().Add(nonGenericType2); 131 | } 132 | List list = stack.Pop(); 133 | Type[] array = list.ToArray(); 134 | Type type = stack2.Pop(); 135 | Type type2 = type.MakeGenericType(array); 136 | if (type2 == null) 137 | { 138 | return null; 139 | } 140 | if (stack.Count > 0) 141 | { 142 | stack.Peek().Add(type2); 143 | } 144 | else 145 | { 146 | stack2.Push(type2); 147 | } 148 | } 149 | else 150 | { 151 | string compilerTypeName4 = stringBuilder.ToString(); 152 | Type nonGenericType3 = GetNonGenericType(compilerTypeName4); 153 | if (nonGenericType3 == null) 154 | { 155 | return null; 156 | } 157 | stack2.Push(nonGenericType3); 158 | stack.Push(new List()); 159 | stringBuilder.Clear(); 160 | } 161 | IL_149: 162 | i++; 163 | continue; 164 | IL_140: 165 | stringBuilder.Append(c); 166 | goto IL_149; 167 | } 168 | if (stack2.Count != 1) 169 | { 170 | throw new ReflectionHelperException("Error constructing generic type '" + compilerTypeName + "'"); 171 | } 172 | return XamlReflectionType.Create(stack2.Pop()); 173 | } 174 | 175 | private static bool IsGenericTypeName(string compilerTypeName) 176 | => compilerTypeName.Contains('<') || compilerTypeName.Contains('`'); 177 | 178 | private static IXamlMember CreateXamlMember(string longMemberName) 179 | { 180 | GetTypeAndMember(longMemberName, out string typeName, out string memberName); 181 | return XamlReflectionMember.Create(memberName, GetXamlTypeInternal(typeName).UnderlyingType); 182 | } 183 | 184 | private static void GetTypeAndMember(string longMemberName, out string typeName, out string memberName) 185 | { 186 | int num = longMemberName.LastIndexOf('.'); 187 | string text = longMemberName[..num]; 188 | string text2 = longMemberName[(num + 1)..]; 189 | typeName = text; 190 | memberName = text2; 191 | } 192 | 193 | private static readonly List> _providers = []; 194 | 195 | private static readonly List _assemblies = 196 | [ 197 | IntrospectionExtensions.GetTypeInfo(typeof(Application)).Assembly.FullName!, 198 | IntrospectionExtensions.GetTypeInfo(typeof(object)).Assembly.FullName!, 199 | // .. Directory.GetFiles(AppContext.BaseDirectory, "*.dll", SearchOption.AllDirectories) 200 | ]; 201 | 202 | private static readonly ConcurrentDictionary _xamlTypeCacheByName = []; 203 | 204 | private static readonly ConcurrentDictionary _xamlTypeCacheByType = []; 205 | } 206 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Reflection; 3 | 4 | namespace Microsoft.UI.Xaml.Markup; 5 | 6 | [DebuggerNonUserCode] 7 | internal static partial class TypeExtensions 8 | { 9 | internal static void EnsureInitialized() 10 | { 11 | Dictionary projectToCompilerTypeName = _projectToCompilerTypeName; 12 | lock (projectToCompilerTypeName) 13 | { 14 | if (_projectToCompilerTypeName.Count == 0) 15 | { 16 | foreach (string text in _projectionNames) 17 | { 18 | string text2 = "System." + text; 19 | _projectToCompilerTypeName.Add(text2, text); 20 | _projectFromCompilerTypeName.Add(text, text2); 21 | } 22 | } 23 | } 24 | } 25 | 26 | public static string GetStandardTypeName(string typeName) 27 | { 28 | EnsureInitialized(); 29 | if (_projectToCompilerTypeName.TryGetValue(typeName, out var value)) 30 | return value; 31 | return typeName; 32 | } 33 | 34 | public static string GetCSharpTypeName(string typeName) 35 | { 36 | EnsureInitialized(); 37 | if (_projectFromCompilerTypeName.TryGetValue(typeName, out var value)) 38 | return value; 39 | return typeName; 40 | } 41 | 42 | public static PropertyInfo? GetStaticProperty(this Type type, string propertyName) 43 | { 44 | foreach (PropertyInfo propertyInfo in IntrospectionExtensions.GetTypeInfo(type).DeclaredProperties) 45 | { 46 | if (propertyInfo.Name.Equals(propertyName)) 47 | return propertyInfo; 48 | } 49 | return null; 50 | } 51 | 52 | public static FieldInfo? GetStaticField(this Type type, string fieldName) 53 | { 54 | foreach (FieldInfo fieldInfo in IntrospectionExtensions.GetTypeInfo(type).DeclaredFields) 55 | { 56 | if (fieldInfo.Name.Equals(fieldName)) 57 | return fieldInfo; 58 | } 59 | return null; 60 | } 61 | 62 | public static string MakeCompilerTypeName(string typeToString) 63 | => typeToString.Replace('[', '<').Replace(']', '>'); 64 | 65 | public static string GetFullGenericNestedName(Type type) 66 | { 67 | string typeName = MakeCompilerTypeName(type.ToString()); 68 | string standardTypeName = GetStandardTypeName(typeName); 69 | if (!IntrospectionExtensions.GetTypeInfo(type).IsGenericType) 70 | return standardTypeName; 71 | 72 | string text = "<"; 73 | string text2 = ">"; 74 | Type[] genericTypeArguments = IntrospectionExtensions.GetTypeInfo(type).GenericTypeArguments; 75 | Type genericTypeDefinition = IntrospectionExtensions.GetTypeInfo(type).GetGenericTypeDefinition(); 76 | string text3 = MakeCompilerTypeName(genericTypeDefinition.ToString()); 77 | text3 = text3.Substring(0, text3.IndexOf('<')); 78 | string text4 = text3; 79 | text4 += text; 80 | for (int i = 0; i < genericTypeArguments.Length; i++) 81 | { 82 | text4 += GetFullGenericNestedName(genericTypeArguments[i]); 83 | if (i < genericTypeArguments.Length - 1) 84 | { 85 | text4 += ", "; 86 | } 87 | } 88 | return text4 + text2; 89 | } 90 | 91 | static readonly Dictionary _projectToCompilerTypeName = []; 92 | static readonly Dictionary _projectFromCompilerTypeName = []; 93 | 94 | private static readonly string[] _projectionNames = 95 | [ 96 | "Byte", 97 | "UInt8", 98 | "SByte", 99 | "Int8", 100 | "Char", 101 | "Char16", 102 | "Single", 103 | "Double", 104 | "Int16", 105 | "Int32", 106 | "Int64", 107 | "UInt16", 108 | "UInt32", 109 | "UInt64", 110 | "Boolean", 111 | "String", 112 | "Object", 113 | "Guid", 114 | "TimeSpan", 115 | "DateTime" 116 | ]; 117 | } 118 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/XamlReflectionMember.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Reflection; 3 | using Windows.UI.Xaml.Markup; 4 | 5 | namespace Microsoft.UI.Xaml.Markup; 6 | 7 | [DebuggerNonUserCode] 8 | internal sealed partial class XamlReflectionMember : IXamlMember 9 | { 10 | public static XamlReflectionMember Create(string memberName, Type declaringType) 11 | { 12 | bool isDependencyProperty = false; 13 | bool isReadOnly = false; 14 | Type type = null; 15 | bool isAttachable = false; 16 | Type targetType = null; 17 | MethodInfo attachableGetterInfo = null; 18 | MethodInfo attachableSetterInfo = null; 19 | PropertyInfo runtimeProperty = declaringType.GetRuntimeProperty(memberName); 20 | if (runtimeProperty != null) 21 | { 22 | type = runtimeProperty.PropertyType; 23 | isReadOnly = !runtimeProperty.CanWrite; 24 | } 25 | PropertyInfo staticProperty = declaringType.GetStaticProperty(memberName + "Property"); 26 | if (staticProperty != null) 27 | { 28 | isDependencyProperty = true; 29 | } 30 | else 31 | { 32 | FieldInfo staticField = declaringType.GetStaticField(memberName + "Property"); 33 | if (staticField != null) 34 | { 35 | isDependencyProperty = true; 36 | } 37 | } 38 | bool flag = false; 39 | bool flag2 = false; 40 | Type type2 = null; 41 | Type type3 = null; 42 | IEnumerable runtimeMethods = RuntimeReflectionExtensions.GetRuntimeMethods(declaringType); 43 | foreach (MethodInfo methodInfo in runtimeMethods) 44 | { 45 | if (flag && flag2) 46 | { 47 | break; 48 | } 49 | if (methodInfo.IsStatic && methodInfo.IsPublic) 50 | { 51 | if (methodInfo.Name.Equals("Set" + memberName)) 52 | { 53 | ParameterInfo[] parameters = methodInfo.GetParameters(); 54 | if (parameters.Length == 2) 55 | { 56 | if (type == null) 57 | { 58 | type = parameters[1].ParameterType; 59 | } 60 | type3 = parameters[0].ParameterType; 61 | flag2 = true; 62 | attachableSetterInfo = methodInfo; 63 | } 64 | } 65 | else if (methodInfo.Name.Equals("Get" + memberName)) 66 | { 67 | ParameterInfo[] parameters2 = methodInfo.GetParameters(); 68 | if (parameters2.Length == 1) 69 | { 70 | type ??= methodInfo.ReturnType; 71 | 72 | type2 = parameters2[0].ParameterType; 73 | flag = true; 74 | attachableGetterInfo = methodInfo; 75 | } 76 | } 77 | } 78 | } 79 | if (flag || flag2) 80 | { 81 | isAttachable = true; 82 | isReadOnly = !flag2; 83 | if (flag) 84 | { 85 | targetType = type2; 86 | } 87 | else if (flag2) 88 | { 89 | targetType = type3; 90 | } 91 | } 92 | 93 | if (type == null) 94 | return null; 95 | 96 | return new XamlReflectionMember(memberName, isDependencyProperty, isReadOnly, type, declaringType, isAttachable, targetType, attachableGetterInfo, attachableSetterInfo); 97 | } 98 | 99 | public string Name { get; } 100 | public bool IsAttachable { get; } 101 | public bool IsDependencyProperty { get; } 102 | public bool IsReadOnly { get; } 103 | 104 | readonly Type _underlyingType; 105 | readonly Type _declaringType; 106 | readonly Type _targetType; 107 | readonly MethodInfo _attachableGetterInfo; 108 | readonly MethodInfo _attachableSetterInfo; 109 | 110 | XamlReflectionMember(string memberName, bool isDependencyProperty, bool isReadOnly, Type underlyingType, Type declaringType, bool isAttachable, Type targetType, MethodInfo attachableGetterInfo, MethodInfo attachableSetterInfo) 111 | { 112 | Name = memberName; 113 | IsDependencyProperty = isDependencyProperty; 114 | IsReadOnly = isReadOnly; 115 | _underlyingType = underlyingType; 116 | _declaringType = declaringType; 117 | IsAttachable = isAttachable; 118 | _targetType = targetType; 119 | _attachableGetterInfo = attachableGetterInfo; 120 | _attachableSetterInfo = attachableSetterInfo; 121 | } 122 | 123 | public IXamlType Type 124 | => ReflectionXamlMetadataProvider.GetXamlTypeInternal(_underlyingType); 125 | 126 | public IXamlType TargetType 127 | => ReflectionXamlMetadataProvider.GetXamlTypeInternal(_targetType); 128 | 129 | public object GetValue(object instance) 130 | { 131 | if (!IsAttachable) 132 | { 133 | PropertyInfo runtimeProperty = RuntimeReflectionExtensions.GetRuntimeProperty(_declaringType, Name); 134 | object obj = runtimeProperty.GetValue(instance); 135 | if (obj == null && runtimeProperty.PropertyType.Equals(typeof(string))) 136 | { 137 | obj = string.Empty; 138 | } 139 | return obj; 140 | } 141 | return _attachableGetterInfo.Invoke(null, new object[] 142 | { 143 | instance 144 | }); 145 | } 146 | 147 | public void SetValue(object instance, object value) 148 | { 149 | if (!IsAttachable) 150 | { 151 | PropertyInfo runtimeProperty = RuntimeReflectionExtensions.GetRuntimeProperty(_declaringType, Name); 152 | if (value == null && runtimeProperty.PropertyType.Equals(typeof(string))) 153 | { 154 | value = string.Empty; 155 | } 156 | runtimeProperty.SetValue(instance, value); 157 | return; 158 | } 159 | if (!IsReadOnly) 160 | { 161 | _attachableSetterInfo.Invoke(null, new object[] 162 | { 163 | instance, 164 | value 165 | }); 166 | return; 167 | } 168 | throw new ReflectionHelperException(string.Concat(new string[] 169 | { 170 | "Attempted to write to read-only attachable property '", 171 | _declaringType.FullName, 172 | ".", 173 | Name, 174 | "'" 175 | })); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /Microsoft.UI.Xaml.Markup/XamlReflectionType.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Runtime.CompilerServices; 5 | using Windows.UI.Xaml.Markup; 6 | 7 | namespace Microsoft.UI.Xaml.Markup; 8 | 9 | [DebuggerNonUserCode] 10 | internal sealed partial class XamlReflectionType : IXamlType, IXamlType2 11 | { 12 | private XamlReflectionType(Type underlyingType) 13 | { 14 | _underlyingType = underlyingType; 15 | _info = IntrospectionExtensions.GetTypeInfo(_underlyingType); 16 | _fullName = TypeExtensions.GetFullGenericNestedName(_underlyingType); 17 | IsMarkupExtension = XamlReflectionType.markupExtTypeInfo.IsAssignableFrom(_info); 18 | RuntimeHelpers.RunClassConstructor(_underlyingType.TypeHandle); 19 | IEnumerable implementedInterfaces = IntrospectionExtensions.GetTypeInfo(_underlyingType).ImplementedInterfaces; 20 | Type type = null; 21 | Type type2 = null; 22 | Type type3 = null; 23 | foreach (Type type4 in implementedInterfaces) 24 | { 25 | string fullName = type4.FullName; 26 | if (type == null && fullName.StartsWith("System.Collections.Generic.ICollection`1")) 27 | { 28 | type = type4; 29 | } 30 | else if (type2 == null && fullName.StartsWith("System.Collections.Generic.IDictionary`2")) 31 | { 32 | type2 = type4; 33 | } 34 | else if (type3 == null && fullName.StartsWith("System.Collections.Generic.IList`1")) 35 | { 36 | type3 = type4; 37 | } 38 | } 39 | bool flag = XamlReflectionType.iListTypeInfo.IsAssignableFrom(_info); 40 | bool flag2 = XamlReflectionType.iDictionaryTypeInfo.IsAssignableFrom(_info); 41 | bool flag3 = XamlReflectionType.iEnumerableTypeInfo.IsAssignableFrom(_info); 42 | IsCollection = (type != null || type3 != null || flag); 43 | IsDictionary = (flag2 || type2 != null); 44 | if (IsDictionary) 45 | { 46 | if (type2 != null) 47 | { 48 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(IntrospectionExtensions.GetTypeInfo(type2).GenericTypeArguments[0]); 49 | KeyType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(IntrospectionExtensions.GetTypeInfo(type2).GenericTypeArguments[1]); 50 | } 51 | else 52 | { 53 | ItemType = (KeyType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeof(object))); 54 | } 55 | } 56 | else if (IsCollection) 57 | { 58 | if (type3 != null) 59 | { 60 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(IntrospectionExtensions.GetTypeInfo(type3).GenericTypeArguments[0]); 61 | } 62 | else if (type != null) 63 | { 64 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(IntrospectionExtensions.GetTypeInfo(type).GenericTypeArguments[0]); 65 | } 66 | else 67 | { 68 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeof(object)); 69 | } 70 | } 71 | if (IsCollection || IsDictionary || flag3) 72 | { 73 | IEnumerable runtimeMethods = RuntimeReflectionExtensions.GetRuntimeMethods(_underlyingType); 74 | IEnumerable enumerable = null; 75 | if (type != null) 76 | { 77 | enumerable = RuntimeReflectionExtensions.GetRuntimeMethods(type); 78 | } 79 | else if (type2 != null) 80 | { 81 | enumerable = RuntimeReflectionExtensions.GetRuntimeMethods(type3); 82 | } 83 | List list; 84 | if (enumerable == null) 85 | { 86 | list = Enumerable.ToList(runtimeMethods); 87 | } 88 | else 89 | { 90 | list = Enumerable.ToList(Enumerable.Concat(runtimeMethods, enumerable)); 91 | } 92 | foreach (MethodInfo methodInfo in list) 93 | { 94 | if (methodInfo.IsPublic && methodInfo.Name.Equals("Add")) 95 | { 96 | ParameterInfo[] parameters = methodInfo.GetParameters(); 97 | if (flag3 && !IsCollection && !IsDictionary) 98 | { 99 | if (parameters.Length == 1) 100 | { 101 | IsCollection = true; 102 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(parameters[0].ParameterType); 103 | } 104 | else if (parameters.Length == 2) 105 | { 106 | IsDictionary = true; 107 | KeyType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(parameters[0].ParameterType); 108 | ItemType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(parameters[1].ParameterType); 109 | } 110 | } 111 | _adderInfo = methodInfo; 112 | break; 113 | } 114 | } 115 | } 116 | IsConstructible = GetIsConstructible(); 117 | IsBindable = HasBindableAttribute(); 118 | } 119 | 120 | public static XamlReflectionType Create(Type typeID) 121 | { 122 | if (typeID == null) 123 | { 124 | return null; 125 | } 126 | return new XamlReflectionType(typeID); 127 | } 128 | 129 | // (get) Token: 0x06000014 RID: 20 RVA: 0x000029F5 File Offset: 0x00000BF5 130 | public string FullName 131 | { 132 | get 133 | { 134 | return _fullName; 135 | } 136 | } 137 | 138 | // (get) Token: 0x06000015 RID: 21 RVA: 0x000029FD File Offset: 0x00000BFD 139 | public Type UnderlyingType 140 | { 141 | get 142 | { 143 | return _underlyingType; 144 | } 145 | } 146 | 147 | // (get) Token: 0x06000016 RID: 22 RVA: 0x00002A08 File Offset: 0x00000C08 148 | public IXamlType BaseType 149 | { 150 | get 151 | { 152 | if (!_gotBaseType) 153 | { 154 | _gotBaseType = true; 155 | if (_info.BaseType == null || _info.BaseType.FullName == "System.Runtime.InteropServices.WindowsRuntime.RuntimeClass") 156 | { 157 | _baseType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeof(object)); 158 | } 159 | else 160 | { 161 | _baseType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(_info.BaseType); 162 | } 163 | } 164 | return _baseType; 165 | } 166 | } 167 | 168 | // (get) Token: 0x06000017 RID: 23 RVA: 0x00002A80 File Offset: 0x00000C80 169 | public IXamlType BoxedType 170 | { 171 | get 172 | { 173 | if (!_gotBoxedType) 174 | { 175 | _gotBoxedType = true; 176 | if (FullName.StartsWith("System.Nullable`1") || FullName.StartsWith("Windows.Foundation.IReference`1")) 177 | { 178 | Type typeID = _info.GenericTypeArguments[0]; 179 | _boxedType = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeID); 180 | } 181 | else 182 | { 183 | _boxedType = null; 184 | } 185 | } 186 | return _boxedType; 187 | } 188 | } 189 | 190 | // (get) Token: 0x06000018 RID: 24 RVA: 0x00002AEC File Offset: 0x00000CEC 191 | public IXamlMember ContentProperty 192 | { 193 | get 194 | { 195 | if (!_gotContentProperty) 196 | { 197 | _gotContentProperty = true; 198 | string stringNamedArgumentFromAttribute = GetStringNamedArgumentFromAttribute("Windows.UI.Xaml.Markup.ContentPropertyAttribute", "Name"); 199 | if (stringNamedArgumentFromAttribute != null) 200 | { 201 | _contentProperty = GetMember(GetStringNamedArgumentFromAttribute("Windows.UI.Xaml.Markup.ContentPropertyAttribute", "Name")); 202 | } 203 | } 204 | return _contentProperty; 205 | } 206 | } 207 | 208 | public IXamlMember GetMember(string name) 209 | { 210 | IXamlMember xamlMember = null; 211 | if (_members == null) 212 | { 213 | _members = new Dictionary(); 214 | } 215 | else if (_members.TryGetValue(name, out xamlMember)) 216 | { 217 | return xamlMember; 218 | } 219 | xamlMember = XamlReflectionMember.Create(name, _underlyingType); 220 | _members.Add(name, xamlMember); 221 | return xamlMember; 222 | } 223 | 224 | // (get) Token: 0x0600001A RID: 26 RVA: 0x00002B91 File Offset: 0x00000D91 225 | public bool IsArray 226 | { 227 | get 228 | { 229 | return _underlyingType.IsArray; 230 | } 231 | } 232 | 233 | // (get) Token: 0x0600001B RID: 27 RVA: 0x00002B9E File Offset: 0x00000D9E 234 | public bool IsCollection { get; } 235 | 236 | // (get) Token: 0x0600001C RID: 28 RVA: 0x00002BA6 File Offset: 0x00000DA6 237 | public bool IsConstructible { get; } 238 | 239 | // (get) Token: 0x0600001D RID: 29 RVA: 0x00002BAE File Offset: 0x00000DAE 240 | public bool IsDictionary { get; } 241 | 242 | // (get) Token: 0x0600001E RID: 30 RVA: 0x00002BB6 File Offset: 0x00000DB6 243 | public bool IsMarkupExtension { get; } 244 | 245 | // (get) Token: 0x0600001F RID: 31 RVA: 0x00002BBE File Offset: 0x00000DBE 246 | public bool IsBindable { get; } 247 | 248 | // (get) Token: 0x06000020 RID: 32 RVA: 0x00002BC6 File Offset: 0x00000DC6 249 | public IXamlType ItemType { get; } 250 | 251 | // (get) Token: 0x06000021 RID: 33 RVA: 0x00002BCE File Offset: 0x00000DCE 252 | public IXamlType KeyType { get; } 253 | 254 | public object ActivateInstance() 255 | => Activator.CreateInstance(_underlyingType); 256 | 257 | public void AddToMap(object instance, object key, object value) 258 | { 259 | _adderInfo.Invoke(instance, new object[] 260 | { 261 | key, 262 | value 263 | }); 264 | } 265 | 266 | public void AddToVector(object instance, object value) 267 | { 268 | _adderInfo.Invoke(instance, new object[] 269 | { 270 | value 271 | }); 272 | } 273 | 274 | public void RunInitializer() 275 | { 276 | RuntimeHelpers.RunClassConstructor(_underlyingType.TypeHandle); 277 | } 278 | 279 | public object CreateFromString(string value) 280 | { 281 | if (!_gotCreateFromStringMethod) 282 | { 283 | _gotCreateFromStringMethod = true; 284 | string stringNamedArgumentFromAttribute = GetStringNamedArgumentFromAttribute("Windows.Foundation.Metadata.CreateFromStringAttribute", "MethodName"); 285 | if (stringNamedArgumentFromAttribute != null) 286 | { 287 | int num = stringNamedArgumentFromAttribute.LastIndexOf('.'); 288 | Type type; 289 | string text; 290 | if (num == -1) 291 | { 292 | type = _underlyingType; 293 | text = stringNamedArgumentFromAttribute; 294 | } 295 | else 296 | { 297 | int num2 = stringNamedArgumentFromAttribute.IndexOf('+'); 298 | if (num2 == -1) 299 | { 300 | string typeName = stringNamedArgumentFromAttribute.Substring(0, num); 301 | string text2 = stringNamedArgumentFromAttribute.Substring(num + 1); 302 | type = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeName).UnderlyingType; 303 | text = text2; 304 | } 305 | else 306 | { 307 | string[] array = stringNamedArgumentFromAttribute.Split(new char[] 308 | { 309 | '+' 310 | }); 311 | string typeName2 = array[0]; 312 | Type type2 = ReflectionXamlMetadataProvider.GetXamlTypeInternal(typeName2).UnderlyingType; 313 | for (int i = 1; i < array.Length - 1; i++) 314 | { 315 | type2 = IntrospectionExtensions.GetTypeInfo(type2).GetDeclaredNestedType(array[i]).AsType(); 316 | } 317 | string text3 = array[array.Length - 1]; 318 | int num3 = text3.LastIndexOf('.'); 319 | string text4 = text3.Substring(0, num3); 320 | string text5 = text3.Substring(num3 + 1); 321 | type = IntrospectionExtensions.GetTypeInfo(type2).GetDeclaredNestedType(text4).AsType(); 322 | text = text5; 323 | } 324 | } 325 | _createFromStringMethod = RuntimeReflectionExtensions.GetRuntimeMethod(type, text, new Type[] 326 | { 327 | typeof(string) 328 | }); 329 | } 330 | } 331 | if (BoxedType != null) 332 | { 333 | object obj = BoxedType.CreateFromString(value); 334 | foreach (ConstructorInfo constructorInfo in _info.DeclaredConstructors) 335 | { 336 | ParameterInfo[] parameters = constructorInfo.GetParameters(); 337 | if (parameters.Length == 1 && parameters[0].ParameterType.Equals(_info.GenericTypeArguments[0])) 338 | { 339 | return constructorInfo.Invoke(new object[] 340 | { 341 | obj 342 | }); 343 | } 344 | } 345 | throw new ReflectionHelperException("Couldn't locate appropriate boxing constructor for boxed type '" + FullName + "'"); 346 | } 347 | if (_createFromStringMethod != null) 348 | { 349 | return _createFromStringMethod.Invoke(null, new object[] 350 | { 351 | value 352 | }); 353 | } 354 | return ParseEnumValue(value); 355 | } 356 | 357 | private object ParseEnumValue(string value) 358 | { 359 | string[] parts = value.Split(new char[] 360 | { 361 | ',' 362 | }); 363 | if (_enumType == null) 364 | { 365 | Type underlyingType = Enum.GetUnderlyingType(_underlyingType); 366 | if (underlyingType.Equals(typeof(sbyte))) 367 | { 368 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.SByte); 369 | } 370 | else if (underlyingType.Equals(typeof(byte))) 371 | { 372 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.Byte); 373 | } 374 | else if (underlyingType.Equals(typeof(short))) 375 | { 376 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.Int16); 377 | } 378 | else if (underlyingType.Equals(typeof(ushort))) 379 | { 380 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.UInt16); 381 | } 382 | else if (underlyingType.Equals(typeof(int))) 383 | { 384 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.Int32); 385 | } 386 | else if (underlyingType.Equals(typeof(uint))) 387 | { 388 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.UInt32); 389 | } 390 | else if (underlyingType.Equals(typeof(long))) 391 | { 392 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.Int64); 393 | } 394 | else if (underlyingType.Equals(typeof(ulong))) 395 | { 396 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.UInt64); 397 | } 398 | else 399 | { 400 | _enumType = new XamlReflectionType.EnumType?(XamlReflectionType.EnumType.Int32); 401 | } 402 | } 403 | XamlReflectionType.EnumType? enumType = _enumType; 404 | if (enumType != null) 405 | { 406 | switch (enumType.GetValueOrDefault()) 407 | { 408 | case XamlReflectionType.EnumType.SByte: 409 | return (sbyte)ProcessEnumStringSigned(parts, _underlyingType); 410 | case XamlReflectionType.EnumType.Byte: 411 | return (byte)ProcessEnumStringUnsigned(parts, _underlyingType); 412 | case XamlReflectionType.EnumType.Int16: 413 | return (short)ProcessEnumStringSigned(parts, _underlyingType); 414 | case XamlReflectionType.EnumType.UInt16: 415 | return (ushort)ProcessEnumStringUnsigned(parts, _underlyingType); 416 | case XamlReflectionType.EnumType.Int32: 417 | return (int)ProcessEnumStringSigned(parts, _underlyingType); 418 | case XamlReflectionType.EnumType.UInt32: 419 | return (uint)ProcessEnumStringUnsigned(parts, _underlyingType); 420 | case XamlReflectionType.EnumType.Int64: 421 | return ProcessEnumStringSigned(parts, _underlyingType); 422 | case XamlReflectionType.EnumType.UInt64: 423 | return ProcessEnumStringUnsigned(parts, _underlyingType); 424 | } 425 | } 426 | throw new ReflectionHelperException("Couldn't resolve underlying enum type for type '" + _underlyingType.FullName + "'"); 427 | } 428 | 429 | private ulong ProcessEnumStringUnsigned(IEnumerable parts, Type underlyingType) 430 | { 431 | ulong num = 0UL; 432 | foreach (string text in parts) 433 | { 434 | object obj = Enum.Parse(underlyingType, text.Trim()); 435 | ulong num2 = Convert.ToUInt64(obj); 436 | num |= num2; 437 | } 438 | return num; 439 | } 440 | 441 | private long ProcessEnumStringSigned(IEnumerable parts, Type underlyingType) 442 | { 443 | long num = 0L; 444 | foreach (string text in parts) 445 | { 446 | object obj = Enum.Parse(underlyingType, text.Trim()); 447 | long num2 = Convert.ToInt64(obj); 448 | num |= num2; 449 | } 450 | return num; 451 | } 452 | 453 | private bool GetIsConstructible() 454 | { 455 | foreach (ConstructorInfo constructorInfo in _info.DeclaredConstructors) 456 | { 457 | ParameterInfo[] parameters = constructorInfo.GetParameters(); 458 | if (parameters.Length == 0) 459 | { 460 | return true; 461 | } 462 | } 463 | return false; 464 | } 465 | 466 | private bool HasBindableAttribute() 467 | { 468 | return HasAttribute("Windows.UI.Xaml.Data.BindableAttribute"); 469 | } 470 | 471 | private string GetStringNamedArgumentFromAttribute(string attributeTypeName, string attributeTypedArgName) 472 | { 473 | foreach (CustomAttributeData customAttributeData in _info.CustomAttributes) 474 | { 475 | if (customAttributeData.AttributeType.FullName == attributeTypeName) 476 | { 477 | foreach (CustomAttributeNamedArgument customAttributeNamedArgument in customAttributeData.NamedArguments) 478 | { 479 | if (customAttributeNamedArgument.MemberName.Equals(attributeTypedArgName)) 480 | { 481 | return customAttributeNamedArgument.TypedValue.Value as string; 482 | } 483 | } 484 | } 485 | } 486 | return null; 487 | } 488 | 489 | private bool HasAttribute(string attrName) 490 | { 491 | foreach (CustomAttributeData customAttributeData in _info.CustomAttributes) 492 | { 493 | if (customAttributeData.AttributeType.FullName == attrName) 494 | { 495 | return true; 496 | } 497 | } 498 | return false; 499 | } 500 | 501 | // Note: this type is marked as 'beforefieldinit'. 502 | static XamlReflectionType() 503 | { 504 | } 505 | 506 | private static TypeInfo iListTypeInfo = IntrospectionExtensions.GetTypeInfo(typeof(IList)); 507 | 508 | private static TypeInfo iDictionaryTypeInfo = IntrospectionExtensions.GetTypeInfo(typeof(IDictionary)); 509 | 510 | private static TypeInfo markupExtTypeInfo = IntrospectionExtensions.GetTypeInfo(typeof(MarkupExtension)); 511 | 512 | private static TypeInfo iEnumerableTypeInfo = IntrospectionExtensions.GetTypeInfo(typeof(IEnumerable)); 513 | 514 | private const string nullableTypeName = "System.Nullable`1"; 515 | 516 | private const string referenceTypeName = "Windows.Foundation.IReference`1"; 517 | 518 | private Type _underlyingType; 519 | 520 | private TypeInfo _info; 521 | 522 | private Dictionary _members; 523 | 524 | private string _fullName; 525 | 526 | private MethodInfo _adderInfo; 527 | 528 | private MethodInfo _createFromStringMethod; 529 | 530 | private bool _gotCreateFromStringMethod; 531 | 532 | private IXamlMember _contentProperty; 533 | 534 | private bool _gotContentProperty; 535 | 536 | private IXamlType _baseType; 537 | 538 | private bool _gotBaseType; 539 | 540 | private IXamlType _boxedType; 541 | 542 | private bool _gotBoxedType; 543 | 544 | private XamlReflectionType.EnumType? _enumType; 545 | 546 | private enum EnumType 547 | { 548 | SByte, 549 | Byte, 550 | Int16, 551 | UInt16, 552 | Int32, 553 | UInt32, 554 | Int64, 555 | UInt64 556 | } 557 | } 558 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ShortDev.Uwp.FullTrust 2 | 3 | Create highly performant UI with `WinUi2` (Uwp) and enjoy the freedom of `Win32`! 4 | You don't need any interop code for the `.GetForCurrentView()` methods. 5 | 6 | ### Problems 7 | - The library does currently not support any Uwp-Frame related apis 8 | - Therefore not frame customization 9 | - Creating a new window is only possible with the library apis 10 | - Pickers still need `IInitializeWithWindow` (See [#11](https://github.com/ShortDevelopment/ShortDev.Uwp.FullTrust/issues/11)) 11 | 12 | ## Setup 13 | 14 | 1. Create new Uwp project (*UI-Project*) 15 | 2. Add `false` in to the project file 16 | 3. Add reference to this library 17 | --- 18 | 5. Create new `netcoreapp3.1` `WinExe` project (*Host-Project*) 19 | 6. Add reference to `Microsoft.Toolkit.Win32.UI.SDK` 20 | 7. Add reference to Uwp project 21 | 8. Add `TargetPlatformVersion` and `AssetTargetFallback` to the project file 22 | 9. Redirect main method to the Uwp main method (See below) 23 | 24 | ### *Host-Project* (netcoreapp3.1) 25 | This is needed for the management of all the dependency and runtime stuff. 26 | Should contain no logic. 27 | ```xml 28 | 29 | 30 | 31 | WinExe 32 | netcoreapp3.1 33 | x86;x64 34 | uap10.0.19041 35 | 10.0.19041 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | ``` 48 | 49 | #### `Program.cs` 50 | ```csharp 51 | public class Program 52 | { 53 | [STAThread] 54 | public static void Main(string[] args) 55 | { 56 | NAMESPACE.Program.Main(args); 57 | } 58 | } 59 | ``` 60 | 61 | ### *UI-Project* (Uwp) 62 | Should contain all logic. 63 | ```xml 64 | 65 | 66 | 67 | 68 | false 69 | 70 | ... 71 | 72 | ``` 73 | 74 | #### `Program.cs` 75 | ```csharp 76 | public class Program 77 | { 78 | [STAThread] 79 | public static void Main(string[] args) 80 | { 81 | FullTrustApplication.Start((_) => new App()); 82 | } 83 | } 84 | ``` 85 | 86 | ## Examples 87 | #### Create New Window 88 | ```csharp 89 | var view = FullTrustApplication.CreateNewView(); 90 | _ = view.CoreWindow.Dispatcher.RunIdleAsync((x) => 91 | { 92 | Window.Current.Content = new MainPage(); 93 | Window.Current.Activate(); 94 | }); 95 | ``` -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/App.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml.XamlTypeInfo; 2 | using ShortDev.Uwp.FullTrust.Xaml; 3 | using Windows.ApplicationModel.Activation; 4 | using Windows.UI.Xaml; 5 | using Windows.UI.Xaml.Markup; 6 | 7 | namespace ShortDev.Uwp.Compose; 8 | 9 | sealed partial class App : FullTrustApplication, IXamlMetadataProvider 10 | { 11 | public App() 12 | { 13 | UnhandledException += ComposeApp_UnhandledException; 14 | } 15 | 16 | private void ComposeApp_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) 17 | { 18 | e.Handled = true; 19 | var ex = e.Exception; 20 | var msg = e.Message; 21 | } 22 | 23 | public required Func ContentFactory { get; set; } 24 | 25 | protected override void OnActivated(IActivatedEventArgs args) 26 | { 27 | // Resources = new Microsoft.UI.Xaml.Controls.XamlControlsResources(); 28 | 29 | Window.Current.Content = ContentFactory(); 30 | Window.Current.Activate(); 31 | } 32 | 33 | readonly XamlControlsXamlMetaDataProvider _provider = new(); 34 | public IXamlType GetXamlType(Type type) 35 | => _provider.GetXamlType(type); 36 | 37 | public IXamlType GetXamlType(string fullName) 38 | => _provider.GetXamlType(fullName); 39 | 40 | public XmlnsDefinition[] GetXmlnsDefinitions() 41 | => _provider.GetXmlnsDefinitions(); 42 | } 43 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/Bindings/RefValue.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace ShortDev.Uwp.Compose.Bindings; 4 | 5 | public sealed partial class RefValue : INotifyPropertyChanged, INotifyPropertyChanging 6 | { 7 | public RefValue(T defaultValue) 8 | => Value = defaultValue; 9 | 10 | public T Value 11 | { 12 | get => field; 13 | set 14 | { 15 | PropertyChanging?.Invoke(this, PropertyChangingEventArgs); 16 | field = value; 17 | PropertyChanged?.Invoke(this, PropertyChangedEventArgs); 18 | } 19 | } 20 | 21 | public event PropertyChangedEventHandler? PropertyChanged; 22 | public event PropertyChangingEventHandler? PropertyChanging; 23 | 24 | static readonly PropertyChangedEventArgs PropertyChangedEventArgs = new(nameof(Value)); 25 | static readonly PropertyChangingEventArgs PropertyChangingEventArgs = new(nameof(Value)); 26 | } 27 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/ComposerExtensions.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Uwp.Compose.Bindings; 2 | using Windows.UI.Xaml; 3 | using Windows.UI.Xaml.Controls.Primitives; 4 | using Windows.UI.Xaml.Data; 5 | 6 | namespace ShortDev.Uwp.Compose; 7 | 8 | public static partial class ComposerExtensions 9 | { 10 | public static T Apply(this T @this, Action action) where T : UIElement 11 | { 12 | action(@this); 13 | return @this; 14 | } 15 | 16 | public static T Bind(this T @this, DependencyProperty target, RefValue refValue, IValueConverter converter) where T : UIElement 17 | => @this.Bind(target, refValue, x => converter.Convert(x, typeof(TValue), null, null)); 18 | 19 | public static T Bind(this T @this, DependencyProperty target, RefValue refValue, Func converter) where T : UIElement 20 | { 21 | SetValue(null, null); 22 | refValue.PropertyChanged += SetValue; 23 | return @this; 24 | 25 | void SetValue(object? sender, EventArgs? e) 26 | { 27 | if (converter is null) 28 | @this.SetValue(target, refValue.Value); 29 | else 30 | @this.SetValue(target, converter(refValue.Value)); 31 | } 32 | } 33 | 34 | private sealed partial class LambdaValueConverter(Func converter) : IValueConverter 35 | { 36 | public object Convert(object value, Type targetType, object parameter, string language) 37 | { 38 | if (value is not TBindingValue refValue) 39 | return value; 40 | 41 | return converter(refValue); 42 | } 43 | 44 | public object ConvertBack(object value, Type targetType, object parameter, string language) 45 | => throw new NotImplementedException(); 46 | } 47 | 48 | public static T Ref(this T @this, ref T reference) 49 | { 50 | reference = @this; 51 | return @this; 52 | } 53 | 54 | public static T Ref(this T @this, RefValue reference) 55 | { 56 | reference.Value = @this; 57 | return @this; 58 | } 59 | 60 | public static T OnClick(this T @this, RoutedEventHandler handler) where T : ButtonBase 61 | { 62 | @this.Click += handler; 63 | return @this; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/Package.appxmanifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 8 | 9 | 13 | 14 | 15 | 16 | 17 | App1 18 | lukas 19 | Assets\StoreLogo.png 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 34 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/Program.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Uwp.Compose; 2 | using Windows.UI; 3 | using Windows.UI.Xaml.Controls; 4 | using Windows.UI.Xaml.Media; 5 | using static ShortDev.Uwp.Compose.Utils; 6 | 7 | Run(() => 8 | { 9 | TextBlock tb = null!; 10 | var counter = Ref(1L); 11 | 12 | return new StackPanel() 13 | { 14 | Orientation = Orientation.Vertical, 15 | Spacing = 5, 16 | Background = Resource("ApplicationPageBackgroundThemeBrush"), 17 | Children = 18 | { 19 | new TextBlock() 20 | .Ref(ref tb) 21 | .Bind(TextBlock.TextProperty, counter, static x => $"Some Text: {x} clicks"), 22 | 23 | new Button() 24 | { 25 | Content = "Click me" 26 | } 27 | .OnClick(async (s, e) => 28 | { 29 | counter.Value++; 30 | tb.Foreground = Brush(Color.FromArgb(255, 255, 100, 100)); 31 | 32 | //FolderPicker picker = new(); 33 | //picker.InitializeWithCoreWindow(); 34 | //await picker.PickSingleFolderAsync(); 35 | 36 | ContentDialog dialog = new() { 37 | Content = new TextBox(), 38 | XamlRoot = tb.XamlRoot 39 | }; 40 | await dialog.ShowAsync(); 41 | }), 42 | 43 | new TextBox() 44 | } 45 | }; 46 | }); 47 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "ShortDev.Uwp.Compose": { 4 | "commandName": "Project", 5 | "nativeDebugging": true 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/ShortDev.Uwp.Compose.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | DISABLE_XAML_GENERATED_MAIN 6 | net9.0-windows10.0.26100.0 7 | 10.0.17763.0 8 | true 9 | true 10 | true 11 | true 12 | app.manifest 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | Designer 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/Utils.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Uwp.Compose.Bindings; 2 | using ShortDev.Uwp.FullTrust.Xaml; 3 | using System.Diagnostics.CodeAnalysis; 4 | using Windows.UI; 5 | using Windows.UI.Xaml; 6 | using Windows.UI.Xaml.Controls; 7 | using Windows.UI.Xaml.Media; 8 | 9 | namespace ShortDev.Uwp.Compose; 10 | 11 | public static class Utils 12 | { 13 | #region Instance 14 | public static T Compose(T instance) where T : UIElement 15 | => instance; 16 | 17 | public static T Compose(T instance, [AllowNull] ref T @ref) where T : UIElement 18 | { 19 | @ref = instance; 20 | return Compose(instance); 21 | } 22 | #endregion 23 | 24 | #region No Instance 25 | public static T Compose() where T : UIElement, new() 26 | => Compose(new()); 27 | 28 | public static T Compose([AllowNull] ref T @ref) where T : UIElement, new() 29 | { 30 | T instance = Compose(); 31 | @ref = instance; 32 | return instance; 33 | } 34 | #endregion 35 | 36 | #region Panel 37 | public static T Compose(T instance, IReadOnlyList children) where T : Panel 38 | { 39 | foreach (var child in children) 40 | instance.Children.Add(child); 41 | 42 | return Compose(instance); 43 | } 44 | 45 | public static T Compose(T instance, [AllowNull] ref T @ref, IReadOnlyList children) where T : Panel 46 | { 47 | @ref = instance; 48 | return Compose(instance, children); 49 | } 50 | #endregion 51 | 52 | #region ContentControl 53 | public static T Compose(T instance, UIElement child) where T : ContentControl 54 | { 55 | instance.Content = child; 56 | return Compose(instance); 57 | } 58 | 59 | public static T Compose(T instance, [AllowNull] ref T @ref, UIElement child) where T : ContentControl 60 | { 61 | @ref = instance; 62 | return Compose(instance, child); 63 | } 64 | #endregion 65 | 66 | public static RefValue Ref(T defaultValue) 67 | => new(defaultValue); 68 | 69 | public static T Resource(string key) 70 | => (T)Application.Current.Resources[key]; 71 | 72 | public static SolidColorBrush Brush(Color color) 73 | => new(color); 74 | 75 | public static Thickness Thickness(double uniformLength) 76 | => new(uniformLength); 77 | 78 | public static void Run(Func contentFactory) 79 | => FullTrustApplication.Start(p => _ = new App() { ContentFactory = contentFactory }); 80 | } 81 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Compose/app.manifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 54 | 62 | 63 | 64 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32616.157 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShortDev.Uwp.FullTrust", "ShortDev.Uwp.FullTrust\ShortDev.Uwp.FullTrust.csproj", "{B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShortDev.Uwp.Compose", "ShortDev.Uwp.Compose\ShortDev.Uwp.Compose.csproj", "{02EA08E9-0FB5-460D-8970-A17D29E2284C}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.UI.Xaml.Markup", "Microsoft.UI.Xaml.Markup\Microsoft.UI.Xaml.Markup.csproj", "{A139A4E8-B783-4BEA-9F8C-5DE093612359}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{4025EDCC-862C-4684-8E9B-502F05387521}" 13 | ProjectSection(SolutionItems) = preProject 14 | Directory.Build.props = Directory.Build.props 15 | EndProjectSection 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShortDev.Uwp.Internal", "ShortDev.Uwp.Internal\ShortDev.Uwp.Internal.csproj", "{67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShortDev.Win32", "ShortDev.Win32\ShortDev.Win32.csproj", "{A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShortDev.Uwp.Node", "ShortDev.Uwp.Node\ShortDev.Uwp.Node.csproj", "{F6619B8B-DF38-4300-9EF9-C7F9A84B426F}" 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Debug|ARM = Debug|ARM 27 | Debug|ARM64 = Debug|ARM64 28 | Debug|x64 = Debug|x64 29 | Debug|x86 = Debug|x86 30 | Release|Any CPU = Release|Any CPU 31 | Release|ARM = Release|ARM 32 | Release|ARM64 = Release|ARM64 33 | Release|x64 = Release|x64 34 | Release|x86 = Release|x86 35 | EndGlobalSection 36 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 37 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|ARM.ActiveCfg = Debug|Any CPU 40 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|ARM.Build.0 = Debug|Any CPU 41 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|ARM64.ActiveCfg = Debug|Any CPU 42 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|ARM64.Build.0 = Debug|Any CPU 43 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|x64.ActiveCfg = Debug|x64 44 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|x64.Build.0 = Debug|x64 45 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|x86.ActiveCfg = Debug|Any CPU 46 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Debug|x86.Build.0 = Debug|Any CPU 47 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|ARM.ActiveCfg = Release|Any CPU 50 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|ARM.Build.0 = Release|Any CPU 51 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|ARM64.ActiveCfg = Release|Any CPU 52 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|ARM64.Build.0 = Release|Any CPU 53 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|x64.ActiveCfg = Release|Any CPU 54 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|x64.Build.0 = Release|Any CPU 55 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|x86.ActiveCfg = Release|Any CPU 56 | {B5454F0B-98B7-4639-BDE4-0A0D1E0F5973}.Release|x86.Build.0 = Release|Any CPU 57 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|ARM.ActiveCfg = Debug|Any CPU 60 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|ARM.Build.0 = Debug|Any CPU 61 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|ARM64.ActiveCfg = Debug|Any CPU 62 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|ARM64.Build.0 = Debug|Any CPU 63 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|x64.ActiveCfg = Debug|x64 64 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|x64.Build.0 = Debug|x64 65 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|x64.Deploy.0 = Debug|x64 66 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|x86.ActiveCfg = Debug|Any CPU 67 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Debug|x86.Build.0 = Debug|Any CPU 68 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|ARM.ActiveCfg = Release|Any CPU 71 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|ARM.Build.0 = Release|Any CPU 72 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|ARM64.ActiveCfg = Release|Any CPU 73 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|ARM64.Build.0 = Release|Any CPU 74 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|x64.ActiveCfg = Release|Any CPU 75 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|x64.Build.0 = Release|Any CPU 76 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|x86.ActiveCfg = Release|Any CPU 77 | {02EA08E9-0FB5-460D-8970-A17D29E2284C}.Release|x86.Build.0 = Release|Any CPU 78 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 79 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|Any CPU.Build.0 = Debug|Any CPU 80 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|ARM.ActiveCfg = Debug|Any CPU 81 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|ARM.Build.0 = Debug|Any CPU 82 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|ARM64.ActiveCfg = Debug|Any CPU 83 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|ARM64.Build.0 = Debug|Any CPU 84 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|x64.ActiveCfg = Debug|x64 85 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|x64.Build.0 = Debug|x64 86 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|x86.ActiveCfg = Debug|Any CPU 87 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Debug|x86.Build.0 = Debug|Any CPU 88 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|Any CPU.ActiveCfg = Release|Any CPU 89 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|Any CPU.Build.0 = Release|Any CPU 90 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|ARM.ActiveCfg = Release|Any CPU 91 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|ARM.Build.0 = Release|Any CPU 92 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|ARM64.ActiveCfg = Release|Any CPU 93 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|ARM64.Build.0 = Release|Any CPU 94 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|x64.ActiveCfg = Release|Any CPU 95 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|x64.Build.0 = Release|Any CPU 96 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|x86.ActiveCfg = Release|Any CPU 97 | {A139A4E8-B783-4BEA-9F8C-5DE093612359}.Release|x86.Build.0 = Release|Any CPU 98 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 99 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|Any CPU.Build.0 = Debug|Any CPU 100 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|ARM.ActiveCfg = Debug|Any CPU 101 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|ARM.Build.0 = Debug|Any CPU 102 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|ARM64.ActiveCfg = Debug|Any CPU 103 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|ARM64.Build.0 = Debug|Any CPU 104 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|x64.ActiveCfg = Debug|x64 105 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|x64.Build.0 = Debug|x64 106 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|x86.ActiveCfg = Debug|Any CPU 107 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Debug|x86.Build.0 = Debug|Any CPU 108 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|Any CPU.ActiveCfg = Release|Any CPU 109 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|Any CPU.Build.0 = Release|Any CPU 110 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|ARM.ActiveCfg = Release|Any CPU 111 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|ARM.Build.0 = Release|Any CPU 112 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|ARM64.ActiveCfg = Release|Any CPU 113 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|ARM64.Build.0 = Release|Any CPU 114 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|x64.ActiveCfg = Release|Any CPU 115 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|x64.Build.0 = Release|Any CPU 116 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|x86.ActiveCfg = Release|Any CPU 117 | {67DE3CA8-EB4D-4FF4-92BF-AA8E425B22E4}.Release|x86.Build.0 = Release|Any CPU 118 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 119 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|Any CPU.Build.0 = Debug|Any CPU 120 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|ARM.ActiveCfg = Debug|Any CPU 121 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|ARM.Build.0 = Debug|Any CPU 122 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|ARM64.ActiveCfg = Debug|Any CPU 123 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|ARM64.Build.0 = Debug|Any CPU 124 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|x64.ActiveCfg = Debug|x64 125 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|x64.Build.0 = Debug|x64 126 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|x86.ActiveCfg = Debug|Any CPU 127 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Debug|x86.Build.0 = Debug|Any CPU 128 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|Any CPU.ActiveCfg = Release|Any CPU 129 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|Any CPU.Build.0 = Release|Any CPU 130 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|ARM.ActiveCfg = Release|Any CPU 131 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|ARM.Build.0 = Release|Any CPU 132 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|ARM64.ActiveCfg = Release|Any CPU 133 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|ARM64.Build.0 = Release|Any CPU 134 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|x64.ActiveCfg = Release|Any CPU 135 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|x64.Build.0 = Release|Any CPU 136 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|x86.ActiveCfg = Release|Any CPU 137 | {A4DB89C9-E4E8-44AA-93A2-5117956C4D9E}.Release|x86.Build.0 = Release|Any CPU 138 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 139 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|Any CPU.Build.0 = Debug|Any CPU 140 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|ARM.ActiveCfg = Debug|Any CPU 141 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|ARM.Build.0 = Debug|Any CPU 142 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|ARM64.ActiveCfg = Debug|Any CPU 143 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|ARM64.Build.0 = Debug|Any CPU 144 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|x64.ActiveCfg = Debug|Any CPU 145 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|x64.Build.0 = Debug|Any CPU 146 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|x86.ActiveCfg = Debug|Any CPU 147 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Debug|x86.Build.0 = Debug|Any CPU 148 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|Any CPU.ActiveCfg = Release|Any CPU 149 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|Any CPU.Build.0 = Release|Any CPU 150 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|ARM.ActiveCfg = Release|Any CPU 151 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|ARM.Build.0 = Release|Any CPU 152 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|ARM64.ActiveCfg = Release|Any CPU 153 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|ARM64.Build.0 = Release|Any CPU 154 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|x64.ActiveCfg = Release|Any CPU 155 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|x64.Build.0 = Release|Any CPU 156 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|x86.ActiveCfg = Release|Any CPU 157 | {F6619B8B-DF38-4300-9EF9-C7F9A84B426F}.Release|x86.Build.0 = Release|Any CPU 158 | EndGlobalSection 159 | GlobalSection(SolutionProperties) = preSolution 160 | HideSolutionNode = FALSE 161 | EndGlobalSection 162 | GlobalSection(ExtensibilityGlobals) = postSolution 163 | SolutionGuid = {94079978-D490-48BD-8069-F095B27A6654} 164 | EndGlobalSection 165 | EndGlobal 166 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Activation/Win32LaunchActivationArgs.cs: -------------------------------------------------------------------------------- 1 | using Windows.ApplicationModel.Activation; 2 | using Windows.UI.Core; 3 | using Windows.UI.ViewManagement; 4 | 5 | namespace ShortDev.Uwp.FullTrust.Activation; 6 | 7 | internal sealed partial class Win32LaunchActivationArgs : IActivatedEventArgs, ILaunchActivatedEventArgs, ILaunchActivatedEventArgs2, IApplicationViewActivatedEventArgs, IPrelaunchActivatedEventArgs 8 | { 9 | public ActivationKind Kind { get; } = ActivationKind.Launch; 10 | 11 | public ApplicationExecutionState PreviousExecutionState { get; } = ApplicationExecutionState.NotRunning; 12 | 13 | public string Arguments { get; } = string.Join(' ', Environment.GetCommandLineArgs()); 14 | 15 | public SplashScreen SplashScreen => throw new NotImplementedException(); 16 | 17 | public string TileId { get; } = "App"; 18 | 19 | public TileActivatedInfo TileActivatedInfo => throw new NotImplementedException(); 20 | 21 | public int CurrentlyShownApplicationViewId { get; } 22 | = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()); 23 | 24 | public bool PrelaunchActivated { get; } = false; 25 | } 26 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Core/CoreWindowExtensions.cs: -------------------------------------------------------------------------------- 1 | using Windows.Storage.Pickers; 2 | using Windows.UI.Core; 3 | using WinRT.Interop; 4 | 5 | namespace ShortDev.Uwp.FullTrust.Core; 6 | 7 | public static class CoreWindowExtensions 8 | { 9 | static nint Hwnd => CoreWindow.GetForCurrentThread().GetHwnd(); 10 | 11 | public static void InitializeWithCoreWindow(this FileOpenPicker picker) 12 | => InitializeWithWindow.Initialize(picker, Hwnd); 13 | 14 | public static void InitializeWithCoreWindow(this FileSavePicker picker) 15 | => InitializeWithWindow.Initialize(picker, Hwnd); 16 | 17 | public static void InitializeWithCoreWindow(this FolderPicker picker) 18 | => InitializeWithWindow.Initialize(picker, Hwnd); 19 | 20 | public static void InitializeWithCoreWindow(this IInitializeWithCoreWindow dialog) 21 | => dialog.Initialize(CoreWindow.GetForCurrentThread()); 22 | } 23 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Core/CoreWindowFactory.cs: -------------------------------------------------------------------------------- 1 | using Internal.Windows.UI.Core; 2 | using System; 3 | using System.ComponentModel; 4 | using System.Diagnostics; 5 | using System.Runtime.InteropServices; 6 | using Windows.Foundation; 7 | using Windows.UI.Core; 8 | using Windows.Win32.Foundation; 9 | using Windows.Win32.UI.WindowsAndMessaging; 10 | 11 | namespace ShortDev.Uwp.FullTrust.Core; 12 | 13 | public static partial class CoreWindowFactory 14 | { 15 | public enum CoreWindowType : int 16 | { 17 | ImmersiveBody = 0, 18 | ImmersiveDock, 19 | ImmersiveHosted, 20 | ImmersiveTest, 21 | ImmersiveBodyActive, 22 | ImmersiveDockActive, 23 | NotImmersive 24 | } 25 | 26 | [DllImport("windows.ui.dll", EntryPoint = "#1500")] 27 | static extern int PrivateCreateCoreWindow( 28 | CoreWindowType windowType, 29 | [MarshalAs(UnmanagedType.BStr)] string windowTitle, 30 | int x, 31 | int y, 32 | uint width, 33 | uint height, 34 | uint dwAttributes, 35 | ref nint hOwnerWindow, 36 | ref Guid riid, 37 | out nint pWindow 38 | ); 39 | 40 | public static CoreWindow CreateCoreWindow(CoreWindowType windowType, string windowTitle) 41 | => CreateCoreWindow(windowType, windowTitle, null); 42 | 43 | public static CoreWindow CreateCoreWindow(CoreWindowType windowType, string windowTitle, Rect? dimensions) 44 | { 45 | var rect = dimensions ?? GenerateDefaultWindowPosition(); 46 | return CreateCoreWindow(windowType, windowTitle, rect, nint.Zero); 47 | } 48 | 49 | public static CoreWindow CreateCoreWindow(CoreWindowType windowType, string windowTitle, Rect dimensions, nint hOwnerWindow, uint dwAttributes = 0) 50 | { 51 | Guid iid = typeof(ICoreWindowInterop).GUID; 52 | Marshal.ThrowExceptionForHR(PrivateCreateCoreWindow(windowType, windowTitle, (int)dimensions.Left, (int)dimensions.Top, (uint)dimensions.Width, (uint)dimensions.Height, dwAttributes, ref hOwnerWindow, ref iid, out var pWindow)); 53 | return CoreWindow.FromAbi(pWindow); 54 | } 55 | 56 | /// 57 | /// 58 | /// 59 | /// 60 | public static unsafe Rect GenerateDefaultWindowPosition() 61 | { 62 | const int CW_USEDEFAULT = unchecked((int)0x80000000); 63 | const string CLASS_NAME = "tmp"; 64 | 65 | var hInstance = (HINSTANCE)Process.GetCurrentProcess().Handle; 66 | 67 | fixed (char* pClassName = CLASS_NAME) 68 | { 69 | WNDCLASSEXW wc = new(); 70 | wc.cbSize = (uint)Marshal.SizeOf(wc); 71 | 72 | wc.lpfnWndProc = (a, b, c, d) => (LRESULT)1; 73 | wc.hInstance = hInstance; 74 | wc.lpszClassName = pClassName; 75 | 76 | RegisterClassEx(wc); 77 | } 78 | 79 | var hwnd = CreateWindowEx( 80 | 0, // Optional window styles. 81 | CLASS_NAME, // Window class 82 | CLASS_NAME, // Window text 83 | WINDOW_STYLE.WS_OVERLAPPEDWINDOW, // Window style 84 | 85 | // Size and position 86 | CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 87 | 88 | HWND.Null, // Parent window 89 | HMENU.Null, // Menu 90 | hInstance, // Instance handle 91 | (void*)0 // Additional application data 92 | ); 93 | if (hwnd == nint.Zero) 94 | throw new Win32Exception(); 95 | 96 | GetWindowRect(hwnd, out var _bounds); 97 | 98 | DestroyWindow(hwnd); 99 | 100 | return new(_bounds.left, _bounds.top, _bounds.right - _bounds.left, _bounds.bottom - _bounds.top); 101 | } 102 | 103 | [LibraryImport("windows.ui.core.textinput.dll", EntryPoint = "#1500")] 104 | private static partial int CreateTextInputProducer( 105 | /* ITextInputConsumer */ nint consumer, 106 | out /* ITextInputProducer */ nint pProducer 107 | ); 108 | 109 | public static ITextInputProducer CreateTextInputProducer(CoreWindow coreWindow) 110 | { 111 | var consumer = coreWindow.As(); 112 | var pConsumer = MarshalInterface.FromManaged(consumer); 113 | Marshal.ThrowExceptionForHR( 114 | CreateTextInputProducer(pConsumer, out var pProducer) 115 | ); 116 | var producer = MarshalInterface.FromAbi(pProducer); 117 | consumer.TextInputProducer = producer; 118 | return producer; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using XamlTheme = Windows.UI.Xaml.ApplicationTheme; 2 | global using XamlWindow = Windows.UI.Xaml.Window; 3 | global using static Windows.Win32.PInvoke; 4 | global using Windows.Win32.System.WinRT; 5 | global using WinRT; -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Internal/XamlSynchronizationContext.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using Windows.UI.Core; 3 | 4 | namespace ShortDev.Uwp.FullTrust.Internal; 5 | 6 | internal sealed class XamlSynchronizationContext(CoreWindow coreWindow) : SynchronizationContext 7 | { 8 | public CoreWindow CoreWindow { get; } = coreWindow; 9 | 10 | public override void Post(SendOrPostCallback d, object? state) 11 | => _ = CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => d?.Invoke(state)); 12 | 13 | public override void Send(SendOrPostCallback d, object? state) 14 | => _ = CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => d?.Invoke(state)); 15 | } 16 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/InteropHelper.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using Windows.UI.Core; 3 | using Windows.Win32.Foundation; 4 | using Windows.Win32.Security; 5 | 6 | namespace ShortDev.Uwp.FullTrust; 7 | 8 | internal static class InteropHelper 9 | { 10 | public static HWND GetHwnd(this XamlWindow window) 11 | => window.CoreWindow.GetHwnd(); 12 | 13 | public static HWND GetHwnd(this CoreWindow coreWindow) 14 | => coreWindow.As().WindowHandle; 15 | 16 | static readonly HANDLE CurrentProcessPseudoToken = (HANDLE)(-4); 17 | public static unsafe bool IsAppContainer 18 | { 19 | get 20 | { 21 | uint result = 0; 22 | uint size = sizeof(uint); 23 | if (!GetTokenInformation(CurrentProcessPseudoToken, TOKEN_INFORMATION_CLASS.TokenIsAppContainer, &result, size, out size)) 24 | throw new Win32Exception(); 25 | 26 | return Convert.ToBoolean(result); 27 | } 28 | } 29 | 30 | public static unsafe bool HasPackageIdentity 31 | { 32 | get 33 | { 34 | uint length = 0; 35 | GetCurrentPackageFullName(ref length, null); 36 | 37 | char* pPkgFamilyName = stackalloc char[(int)length]; 38 | 39 | var err = GetCurrentPackageFullName(ref length, new PWSTR(pPkgFamilyName)); 40 | if (err == WIN32_ERROR.NO_ERROR) 41 | return true; 42 | 43 | if (err == WIN32_ERROR.APPMODEL_ERROR_NO_PACKAGE) 44 | return false; 45 | 46 | throw new Win32Exception(); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/NativeMethods.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://aka.ms/CsWin32.schema.json", 3 | "useSafeHandles": false, 4 | "allowMarshaling": true 5 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/NativeMethods.txt: -------------------------------------------------------------------------------- 1 | SetWindowSubclass 2 | RemoveWindowSubclass 3 | DefSubclassProc 4 | DefWindowProc 5 | DwmDefWindowProc 6 | 7 | DwmExtendFrameIntoClientArea 8 | SetWindowTheme 9 | 10 | NCCALCSIZE_PARAMS 11 | SendMessage 12 | ReleaseCapture 13 | EnableMouseInPointer 14 | WM_NCLBUTTONDOWN 15 | ScreenToClient 16 | GetDpiForWindow 17 | 18 | RegisterClassEx 19 | CreateWindowEx 20 | GetWindowRect 21 | DestroyWindow 22 | 23 | SetForegroundWindow 24 | SetWindowPos 25 | SetWindowLong 26 | GetWindowLong 27 | ShowWindow 28 | PostMessage 29 | 30 | WM_CLOSE 31 | WM_DESTROY 32 | WM_NCCALCSIZE 33 | WM_NCHITTEST 34 | WM_ACTIVATE 35 | 36 | LoadLibraryExW 37 | FreeLibrary 38 | 39 | CreateDispatcherQueueController 40 | 41 | RoGetActivationFactory 42 | CoCreateInstance 43 | WindowsCreateStringReference 44 | 45 | ICoreWindowInterop 46 | GetTokenInformation 47 | GetCurrentPackageFullName -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/ShortDev.Uwp.FullTrust.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0-windows10.0.22621.0 5 | true 6 | 7 | 8 | 9 | 10 | 0.2.0 11 | Lukas Kurz 12 | ShortDevelopment 13 | https://github.com/ShortDevelopment/ShortDev.Uwp.FullTrust 14 | Readme.md 15 | https://github.com/ShortDevelopment/ShortDev.Uwp.FullTrust 16 | uwp;full-trust;win32;corewindow 17 | LICENSE 18 | Create a performant WinUI application with Uwp and CoreWindow and run as full-trust win32 19 | 20 | 21 | 22 | 23 | True 24 | 25 | 26 | 27 | True 28 | \ 29 | 30 | 31 | 32 | 33 | 34 | 35 | all 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Xaml/FullTrustApplication.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Uwp.FullTrust.Activation; 2 | using ShortDev.Uwp.Internal; 3 | using System.Runtime.InteropServices; 4 | using Windows.ApplicationModel; 5 | using Windows.ApplicationModel.Activation; 6 | using Windows.ApplicationModel.Core; 7 | using Windows.UI.Xaml; 8 | using Windows.Win32.Foundation; 9 | 10 | namespace ShortDev.Uwp.FullTrust.Xaml; 11 | 12 | public abstract class FullTrustApplication : Application 13 | { 14 | // https://github.com/CommunityToolkit/Microsoft.Toolkit.Win32/blob/6fb2c3e00803ea563af20f6bc9363091b685d81f/Microsoft.Toolkit.Win32.UI.XamlApplication/XamlApplication.cpp#L140C5-L150 15 | static readonly List _preloadInstances = []; 16 | static FullTrustApplication() 17 | { 18 | if (InteropHelper.IsAppContainer) 19 | return; 20 | 21 | foreach (var lib in new[] { "twinapi.appcore.dll", "threadpoolwinrt.dll", }) 22 | { 23 | var instance = LoadLibraryEx(lib, 0); 24 | _preloadInstances.Add(instance); 25 | } 26 | } 27 | 28 | ~FullTrustApplication() 29 | { 30 | foreach (var instance in _preloadInstances) 31 | FreeLibrary(instance); 32 | } 33 | 34 | /// 35 | /// Provides the entry point and requests initialization of the application.
36 | /// Use the callback to instantiate the Application class. 37 | ///
38 | /// Custom . 39 | [MTAThread] 40 | public static void Start([In] ApplicationInitializationCallback callback, XamlWindowConfig? windowConfig = null) 41 | { 42 | if (InteropHelper.IsAppContainer) 43 | { 44 | Application.Start(callback); 45 | return; 46 | } 47 | 48 | ThrowOnAlreadyRunning(); 49 | 50 | // Application singleton is created here 51 | callback(null); 52 | IsRunning = true; 53 | 54 | //CreateDispatcherQueueController(new() 55 | //{ 56 | // dwSize = (uint)Marshal.SizeOf(), 57 | // apartmentType = DISPATCHERQUEUE_THREAD_APARTMENTTYPE.DQTAT_COM_ASTA, 58 | // threadType = DISPATCHERQUEUE_THREAD_TYPE.DQTYPE_THREAD_CURRENT 59 | //}, out var dispatcherController).ThrowOnFailure(); 60 | 61 | CreateNewUIThread(() => 62 | { 63 | windowConfig ??= XamlWindowConfig.Default; 64 | 65 | // Create XamlWindow 66 | XamlWindowFactory.CreateNewWindowInternal(windowConfig, out _, out var frameworkView); 67 | 68 | IActivatedEventArgs activationArgs; 69 | if (InteropHelper.HasPackageIdentity) 70 | activationArgs = AppInstance.GetActivatedEventArgs(); 71 | else 72 | activationArgs = new Win32LaunchActivationArgs(); 73 | Current.OnAppActivated(activationArgs); 74 | 75 | // Run message loop 76 | frameworkView.Run(); 77 | frameworkView.Uninitialize(); 78 | }).Join(); 79 | } 80 | 81 | public static bool IsRunning { get; private set; } = false; 82 | static void ThrowOnAlreadyRunning() 83 | { 84 | if (IsRunning) 85 | throw new InvalidOperationException($"Only one instance of \"{nameof(Application)}\" is allowed!"); 86 | } 87 | 88 | public static Thread CreateNewUIThread(Action callback) 89 | { 90 | ArgumentNullException.ThrowIfNull(callback); 91 | 92 | Thread thread = new(() => callback()); 93 | thread.SetApartmentState(ApartmentState.STA); 94 | thread.Start(); 95 | return thread; 96 | } 97 | 98 | #region "CreateNewView" 99 | /// 100 | /// Creates a new view for the app. 101 | /// 102 | public static CoreApplicationView CreateNewView() 103 | => CreateNewView(XamlWindowConfig.Default); 104 | 105 | /// 106 | public static CoreApplicationView CreateNewView(XamlWindowConfig windowConfig) 107 | { 108 | CoreApplicationView? coreAppView = null; 109 | 110 | AutoResetEvent @event = new(false); 111 | CreateNewUIThread(() => 112 | { 113 | var window = XamlWindowFactory.CreateNewWindowInternal(windowConfig, out coreAppView, out var frameworkView); 114 | 115 | @event.Set(); 116 | 117 | // Run message loop 118 | frameworkView.Run(); 119 | frameworkView.Uninitialize(); 120 | }); 121 | @event.WaitOne(); 122 | 123 | return coreAppView!; 124 | } 125 | #endregion 126 | } 127 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Xaml/XamlWindowConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Windows.ApplicationModel; 3 | using Windows.Foundation; 4 | 5 | namespace ShortDev.Uwp.FullTrust.Xaml; 6 | 7 | public class XamlConfig 8 | { 9 | public XamlTheme Theme { get; set; } = XamlTheme.Light; 10 | public bool HasTransparentBackground { get; set; } = false; 11 | } 12 | 13 | public sealed class XamlWindowConfig(string title) : XamlConfig 14 | { 15 | public static XamlWindowConfig Default 16 | { 17 | get 18 | { 19 | string windowTitle = Process.GetCurrentProcess().ProcessName; 20 | try 21 | { 22 | windowTitle = Package.Current?.DisplayName ?? windowTitle; 23 | } 24 | catch { } 25 | return new(windowTitle); 26 | } 27 | } 28 | 29 | public string Title { get; } = title; 30 | public bool HasWin32Frame { get; set; } = true; 31 | public bool HasWin32TitleBar { get; set; } = true; 32 | public bool IsTopMost { get; set; } = false; 33 | public bool IsVisible { get; set; } = false; 34 | public Rect? Bounds { get; set; } = null; 35 | } 36 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Xaml/XamlWindowExtensions.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Win32.Windowing; 2 | 3 | namespace ShortDev.Uwp.FullTrust.Xaml; 4 | 5 | public static class XamlWindowExtensions 6 | { 7 | public static WindowSubclass GetSubclass(this XamlWindow window) 8 | => WindowSubclass.Attach(window.GetHwnd(), throwIfExists: false); 9 | } 10 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/Xaml/XamlWindowFactory.cs: -------------------------------------------------------------------------------- 1 | using Internal.Windows.ApplicationModel.Core; 2 | using Internal.Windows.UI.Xaml; 3 | using Internal.Windows.UI.Xaml.Hosting; 4 | using ShortDev.Uwp.FullTrust.Core; 5 | using ShortDev.Uwp.FullTrust.Internal; 6 | using ShortDev.Win32.Windowing; 7 | using Windows.ApplicationModel.Core; 8 | using Windows.UI.Core; 9 | using Windows.UI.Xaml; 10 | 11 | namespace ShortDev.Uwp.FullTrust.Xaml; 12 | 13 | public static class XamlWindowFactory 14 | { 15 | /// 16 | /// Creates new on current thread.
17 | /// Only one window is allowed per thread!
18 | /// A will be attached automatically. 19 | ///
20 | public static XamlWindow CreateNewWindow(XamlWindowConfig config) 21 | => CreateNewWindowInternal(config, out _, out _); 22 | 23 | public static XamlWindow Attach(nint hwnd, XamlConfig config) 24 | { 25 | PrepareWindowInternal(Win32.Windowing.Window.FromHwnd(hwnd)); 26 | 27 | // Window will be created here (It attaches a subclass to CoreWindow) 28 | var presenter = XamlPresenter.CreateFromHwnd((int)hwnd); 29 | presenter.InitializePresenterWithTheme(config.Theme); 30 | presenter.TransparentBackground = config.HasTransparentBackground; 31 | 32 | return XamlWindow.Current; 33 | } 34 | 35 | internal static CoreWindow PrepareNewCoreWindowInternal(XamlWindowConfig config, out CoreApplicationView coreView, out Win32.Windowing.Window win32Window) 36 | { 37 | var coreApplicationPrivate = CoreApplication.As(); 38 | // Create dummy "CoreApplicationView" for "CoreWindow" constructor 39 | coreApplicationPrivate.CreateNonImmersiveView(); 40 | 41 | // Create "CoreWindow" 42 | CoreWindow coreWindow = CoreWindowFactory.CreateCoreWindow(CoreWindowFactory.CoreWindowType.NotImmersive, config.Title, config.Bounds); 43 | 44 | // Create "CoreApplicationView" 45 | coreView = coreApplicationPrivate.CreateNonImmersiveView(); 46 | 47 | // Create "TextInputProducer" to fix text input in "ContentDialog" 48 | _ = CoreWindowFactory.CreateTextInputProducer(coreWindow); 49 | 50 | // Enable async / await 51 | SynchronizationContext.SetSynchronizationContext(new XamlSynchronizationContext(coreWindow)); 52 | 53 | win32Window = Win32.Windowing.Window.FromHwnd(coreWindow.GetHwnd()); 54 | PrepareWindowInternal(win32Window); 55 | 56 | return coreWindow; 57 | } 58 | 59 | internal static XamlWindow CreateNewWindowInternal(XamlWindowConfig config, out CoreApplicationView coreView, out FrameworkView frameworkView) 60 | { 61 | var coreWindow = PrepareNewCoreWindowInternal(config, out coreView, out var win32Window); 62 | 63 | if (!config.IsVisible) 64 | { 65 | win32Window.IsCloaked = true; 66 | win32Window.ShowInTaskBar = false; 67 | } 68 | 69 | // Mount Xaml rendering 70 | frameworkView = new(); 71 | frameworkView.Initialize(coreView); 72 | frameworkView.SetWindow(coreWindow); 73 | 74 | var window = XamlWindow.Current; 75 | 76 | // A XamlWindow inside a Win32 process is transparent by default 77 | // (See Windows.UI.Xaml.dll!DirectUI::DXamlCore::ConfigureCoreWindow) 78 | // This is to provide a consistent behavior across platforms 79 | window.As().TransparentBackground = config.HasTransparentBackground; 80 | // Application.Current.RequestedTheme = config.Theme; 81 | 82 | // Attach subclass to customize behavior of "CoreWindow" 83 | // Our subclass has to be attached after "FrameworkView"! 84 | WindowSubclass subclass = WindowSubclass.Attach(window.GetHwnd()); 85 | 86 | // Sync settings from "XamlWindowConfig" 87 | win32Window.HasWin32Frame = config.HasWin32Frame; 88 | win32Window.IsTopMost = config.IsTopMost; 89 | subclass.HasWin32TitleBar = config.HasWin32TitleBar; 90 | 91 | if (!config.IsVisible) 92 | { 93 | win32Window.Hide(); 94 | win32Window.IsCloaked = false; 95 | win32Window.ShowInTaskBar = true; 96 | } 97 | else 98 | { 99 | // Show window 100 | coreWindow.Activate(); 101 | win32Window.BringToFront(); 102 | } 103 | 104 | return window; 105 | } 106 | 107 | static void PrepareWindowInternal(Win32.Windowing.Window window) 108 | { 109 | // Enable acrylic "HostBackdropBrush" 110 | window.EnableHostBackdropBrush(); 111 | 112 | EnableMouseInPointer(true); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /ShortDev.Uwp.FullTrust/readme.txt: -------------------------------------------------------------------------------- 1 | # Changes `0.1.7` 2 | 3 | ## Deprecation 4 | - You should use `XamlWindowSubclass.Win32Window` to customize the win32 window frame 5 | 6 | ## New Features 7 | - Ability to set explicit window bounds on creation. 8 | See `XamlWindowConfig.Bounds` 9 | 10 | ## Changed Behavior 11 | - Window is no longer visible by default 12 | You have to set `XamlWindowConfig.IsVisible = true` or call `Window.Activate()` 13 | 14 | 15 | # Changes `0.1.6` 16 | 17 | ## Fixes 18 | - Acrylic HostBackdropBrush is now working 19 | 20 | ## New Features 21 | - Expose some internal apis 22 | 23 | ## Changed Behavior 24 | - Window is no longer transparent by default -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/.gitignore: -------------------------------------------------------------------------------- 1 | lib/ -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using Windows.ApplicationModel.Activation; 3 | using Windows.UI.Xaml; 4 | using WinRT; 5 | 6 | namespace ShortDev.Uwp.Internal; 7 | 8 | public static class Extensions 9 | { 10 | [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "OnActivated")] 11 | static extern void OnActivated(Application app, IActivatedEventArgs args); 12 | 13 | public static void OnAppActivated(this Application @this, IActivatedEventArgs args) 14 | { 15 | OnActivated(@this, args); 16 | 17 | return; 18 | 19 | var app = (IApplicationOverrides)@this; 20 | app.OnActivated(args); 21 | 22 | // https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/get-activation-info-for-packaged-apps#supported-activation-types 23 | switch (args.Kind) 24 | { 25 | case ActivationKind.ShareTarget: 26 | app.OnShareTargetActivated(args.As()); 27 | break; 28 | case ActivationKind.File: 29 | app.OnFileActivated(args.As()); 30 | break; 31 | case ActivationKind.Launch: 32 | app.OnLaunched(args.As()); 33 | break; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/ShortDev.Uwp.Internal.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0-windows10.0.22621.0 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Internal;Windows.UI.Xaml.IApplicationOverrides 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | <_IdlInputs Include="idl/*.idl" /> 23 | <_WinmdTmpOutputs Include="lib/*.winmd" /> 24 | 25 | 26 | 27 | 28 | C:\Windows\System32\WinMetadata 29 | 10.0.22621.0 30 | C:\Program Files (x86)\Windows Kits\10 31 | $(WinSdkBasePath)\Include\$(WinSdkVersion) 32 | /I "$(WinSdkIncludePath)\winrt" /I "$(WinSdkIncludePath)\shared" /I "$(WinSdkIncludePath)\um" 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/idl/Internal.Windows.ApplicationModel.Core.idl: -------------------------------------------------------------------------------- 1 | import "inspectable.idl"; 2 | import "Windows.UI.Core.idl"; 3 | import "Windows.ApplicationModel.Core.idl"; 4 | 5 | namespace Internal.Windows.ApplicationModel.Core 6 | { 7 | [version(1.0)] 8 | [uuid(6090202d-2843-4ba5-9b0d-fc88eecd9ce5)] 9 | interface ICoreApplicationPrivate2 : IInspectable 10 | { 11 | HRESULT InitializeForAttach(); 12 | 13 | HRESULT WaitForActivate([out, retval] Windows.UI.Core.CoreWindow** coreWindow); 14 | 15 | HRESULT CreateNonImmersiveView([out, retval] Windows.ApplicationModel.Core.CoreApplicationView** coreView); 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/idl/Internal.Windows.UI.Core.idl: -------------------------------------------------------------------------------- 1 | import "inspectable.idl"; 2 | import "Windows.System.idl"; 3 | 4 | namespace Internal.Windows.UI.Core 5 | { 6 | [version(1.0)] 7 | enum CoreWindowType 8 | { 9 | IMMERSIVE_BODY = 0, 10 | IMMERSIVE_DOCK, 11 | IMMERSIVE_HOSTED, 12 | IMMERSIVE_TEST, 13 | IMMERSIVE_BODY_ACTIVE, 14 | IMMERSIVE_DOCK_ACTIVE, 15 | NOT_IMMERSIVE 16 | }; 17 | 18 | [version(1.0)] 19 | [uuid(CD292360-2763-4085-8A9F-74B224A29175)] 20 | interface ICoreWindowFactory : IInspectable 21 | { 22 | HRESULT CreateCoreWindow(HSTRING windowTitle, [out][retval] Windows.UI.Core.CoreWindow** window); 23 | [propget] HRESULT WindowReuseAllowed([out][retval] boolean* value); 24 | }; 25 | 26 | [version(1.0)] 27 | [uuid(954460a2-2cf6-4a32-a6c2-26a34c888804)] 28 | interface ITextInputProducer : IInspectable 29 | { 30 | [propget] HRESULT IsInputEnabled([out][retval] boolean* value); 31 | [propput] HRESULT IsInputEnabled([in] boolean value); 32 | [propget] HRESULT HasFocus([out][retval] boolean* value); 33 | [propput] HRESULT HasFocus([in] boolean value); 34 | [propget] HRESULT MessageHandled([out][retval] boolean* value); 35 | [propget] HRESULT CurrentKeyEventType([out][retval] /*Windows.UI.Core.KeyEventType*/ int* value); 36 | HRESULT GetAsyncKeyState([in] Windows.System.VirtualKey key, [out][retval] Windows.UI.Core.CoreVirtualKeyStates* value); 37 | HRESULT GetKeyState([in] Windows.System.VirtualKey key, [out][retval] Windows.UI.Core.CoreVirtualKeyStates* value); 38 | HRESULT GetCurrentKeyEventDeviceId([out][retval] HSTRING* value); 39 | }; 40 | 41 | [version(1.0)] 42 | [uuid(4514e4be-c609-4eeb-96eb-3351ce29e4ef)] 43 | interface ITextInputProducerInternal : IInspectable // IUnknown !! 44 | { 45 | // HRESULT GetEndpoint(void*); 46 | // HRESULT RequestSoftwareKeyboardVisibilityChange(uchar, uchar*); 47 | // HRESULT RegisterKeyEventListener(IKeyEventListener*); 48 | // HRESULT UnregisterKeyEventListener(); 49 | // HRESULT GetTextServicesManager(Windows::UI::Text::Core::ICoreTextServicesManager**); 50 | // HRESULT SetKeyProcessingFlags(unsigned short); 51 | // HRESULT DepartFocus(Windows::UI::Core::INavigationFocusEventArgs*); 52 | // HRESULT StartNavigateFocus(unsigned int); 53 | // HRESULT SetKeyDownHandled(); 54 | // HRESULT CurrentKeyToUnicode(unsigned short*); 55 | // HRESULT OnWindowEnabled(boolean); 56 | // HRESULT GetTextForCurrentKey(ushort*, int); 57 | // HRESULT GetKeyNameTextForCurrentKey(ushort*, int); 58 | // HRESULT GetDeadCharacterForCurrentKey(ushort*); 59 | // HRESULT SetProcessIDDelegation(uint, InputDelegationScenario, bool); 60 | // HRESULT SetViewIDDelegation(uint, InputDelegationScenario, bool); 61 | // HRESULT ConfigureHostRightsForComponent(Windows::UI::Core::HostRightFlags, Windows::UI::Core::HostRightFlags); 62 | // HRESULT NavigateFocusComplete(_GUID, uchar); 63 | // HRESULT SetTextVirtualizationParameters(void*, _GUID); 64 | }; 65 | 66 | [version(1.0)] 67 | [uuid(a9d00ab3-2fef-41a0-b0ad-4b2129ea2663)] 68 | interface ITextInputConsumer : IInspectable 69 | { 70 | [propget] HRESULT TextInputProducer([out][retval] ITextInputProducer** value); 71 | [propput] HRESULT TextInputProducer([in] ITextInputProducer* value); 72 | HRESULT InvokeAcceleratorKeyEventHandlers(); 73 | HRESULT InvokeKeyDownEventHandlers(); 74 | HRESULT InvokeKeyUpEventHandlers(); 75 | HRESULT InvokeCharacterReceivedEventHandlers(); 76 | HRESULT InvokeSystemKeyDownEventHandlers(); 77 | HRESULT InvokeSystemKeyUpEventHandlers(); 78 | HRESULT InvokeNavigationFocusEventHandlers(); 79 | HRESULT OnTextInputProducerFocusChanged(); 80 | HRESULT OnEnableNonCUIDepartFocus(); 81 | }; 82 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/idl/Internal.Windows.UI.WindowManagement.idl: -------------------------------------------------------------------------------- 1 | import "inspectable.idl"; 2 | 3 | namespace Windows.UI.WindowManagement 4 | { 5 | [version(1.0)] 6 | [uuid(b74ea3bc-43c1-521f-9c75-e5c15054d78c)] 7 | interface IApplicationWindow_HwndInterop : IInspectable 8 | { 9 | [propget] HRESULT WindowHandle([out, retval] int* hwnd); 10 | }; 11 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/idl/Internal.Windows.UI.Xaml.Hosting.idl: -------------------------------------------------------------------------------- 1 | import "inspectable.idl"; 2 | import "Windows.UI.Core.idl"; 3 | import "Windows.UI.Xaml.idl"; 4 | 5 | namespace Internal.Windows.UI.Xaml.Hosting 6 | { 7 | runtimeclass XamlPresenter; 8 | 9 | [version(1.0)] 10 | [exclusiveto(XamlPresenter)] 11 | [uuid(8438b07a-9ce8-4e22-ab5d-811d84699566)] 12 | interface IXamlPresenter : IInspectable 13 | { 14 | [propget] HRESULT Content([out, retval] Windows.UI.Xaml.UIElement** value); 15 | [propput] HRESULT Content([in] Windows.UI.Xaml.UIElement* value); 16 | HRESULT SetAtlasSizeHint([in] unsigned int width, [in] unsigned int height); 17 | HRESULT InitializePresenter(); 18 | }; 19 | 20 | [version(1.0)] 21 | [exclusiveto(XamlPresenter)] 22 | [uuid(1114f710-6d30-4572-b24e-c81cf25f0fa5)] 23 | interface IXamlPresenter2 : IInspectable 24 | { 25 | [propget] HRESULT Resources([out, retval] Windows.UI.Xaml.ResourceDictionary** value); 26 | [propput] HRESULT Resources([in] Windows.UI.Xaml.ResourceDictionary* value); 27 | [propget] HRESULT Bounds([out, retval] Windows.Foundation.Rect* value); 28 | [propget] HRESULT RequestedTheme([out, retval] Windows.UI.Xaml.ApplicationTheme* value); 29 | [propput] HRESULT RequestedTheme([in] Windows.UI.Xaml.ApplicationTheme value); 30 | [propget] HRESULT TransparentBackground([out, retval] boolean* value); 31 | [propput] HRESULT TransparentBackground([in] boolean value); 32 | HRESULT InitializePresenterWithTheme([in] Windows.UI.Xaml.ApplicationTheme requestedTheme); 33 | HRESULT SetCaretWidth([in] int width); 34 | }; 35 | 36 | [version(1.0)] 37 | [exclusiveto(XamlPresenter)] 38 | [uuid(5c6ef05e-f60d-4433-8bc6-40586456afeb)] 39 | interface IXamlPresenterStatics : IInspectable 40 | { 41 | HRESULT CreateFromHwnd([in] int hwnd, [out, retval] XamlPresenter** presenter); 42 | }; 43 | 44 | [version(1.0)] 45 | [exclusiveto(XamlPresenter)] 46 | [uuid(d0c1e6c3-1d35-4770-9c3b-e3ff2eefcc25)] 47 | interface IXamlPresenterStatics2 : IInspectable 48 | { 49 | [propget] HRESULT Current([out, retval] XamlPresenter** value); 50 | }; 51 | 52 | [version(1.0)] 53 | [exclusiveto(XamlPresenter)] 54 | [uuid(a49dea01-9e75-49f0-beee-ef1592fbc82b)] 55 | interface IXamlPresenterStatics3 : IInspectable 56 | { 57 | HRESULT CreateFromCoreWindow([in] Windows.UI.Core.CoreWindow* coreWindow, [out, retval] XamlPresenter** presenter); 58 | }; 59 | 60 | [version(1.0)] 61 | [static(IXamlPresenterStatics, 1)] 62 | [static(IXamlPresenterStatics2, 1)] 63 | [static(IXamlPresenterStatics3, 1)] 64 | runtimeclass XamlPresenter 65 | { 66 | [default] interface IXamlPresenter; 67 | interface IXamlPresenter2; 68 | }; 69 | 70 | runtimeclass XamlRuntime; 71 | 72 | [version(1.0)] 73 | [uuid(C805B0C0-6210-4E4F-B76A-E894E8B1A4AD)] 74 | [exclusiveto(XamlRuntime)] 75 | interface IXamlRuntimeStatics : IInspectable 76 | { 77 | [propget] HRESULT EnableImmersiveColors([out][retval] boolean* value); 78 | [propput] HRESULT EnableImmersiveColors([in] boolean value); 79 | [propget] HRESULT EnableWebView([out][retval] boolean* value); 80 | [propput] HRESULT EnableWebView([in] boolean value); 81 | }; 82 | 83 | [version(1.0)] 84 | [static(IXamlRuntimeStatics, 1)] 85 | runtimeclass XamlRuntime 86 | { 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Internal/idl/Internal.Windows.UI.Xaml.idl: -------------------------------------------------------------------------------- 1 | import "inspectable.idl"; 2 | 3 | namespace Internal.Windows.UI.Xaml 4 | { 5 | [version(1.0)] 6 | struct WindowCreationParameters 7 | { 8 | unsigned int Left; 9 | unsigned int Top; 10 | unsigned int Width; 11 | unsigned int Height; 12 | boolean TransparentBackground; 13 | boolean IsCoreNavigationClient; 14 | }; 15 | 16 | [version(1.0)] 17 | [uuid(06636c29-5a17-458d-8ea2-2422d997a922)] 18 | interface IWindowPrivate : IInspectable 19 | { 20 | [propget] HRESULT TransparentBackground([out][retval] boolean* value); 21 | [propput] HRESULT TransparentBackground([in] boolean value); 22 | HRESULT Show(); 23 | HRESULT Hide(); 24 | HRESULT MoveWindow(int x, int h, int width, int height); 25 | }; 26 | } -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/App.xaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.JavaScript.NodeApi; 2 | global using Windows.UI.Xaml; 3 | global using Windows.UI.Xaml.Controls; 4 | global using Windows.UI.Xaml.Markup; 5 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/Initializer.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.Loader; 4 | 5 | namespace ShortDev.Uwp.Node; 6 | internal static class Initializer 7 | { 8 | public static string BaseDirectory { get; private set; } = null!; 9 | 10 | [ModuleInitializer] 11 | public static async void Main() 12 | { 13 | Debugger.Launch(); 14 | 15 | var assembly = typeof(XamlHelper).Assembly; 16 | BaseDirectory = Path.GetDirectoryName(assembly.Location)!; 17 | var loadContext = AssemblyLoadContext.GetLoadContext(assembly)!; 18 | foreach (var filePath in Directory.EnumerateFiles(BaseDirectory, "*.dll", SearchOption.TopDirectoryOnly)) 19 | { 20 | try 21 | { 22 | loadContext.LoadFromAssemblyPath(filePath); 23 | } 24 | catch { } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/ShortDev.Uwp.Node.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0-windows10.0.22621.0 5 | Nullable 6 | true 7 | 8 | 9 | 10 | win-x64 11 | x64 12 | $(RuntimeIdentifier).pubxml 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | PreserveNewest 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/WinUIApp.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml.XamlTypeInfo; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace ShortDev.Uwp.Node; 5 | internal sealed class WinUIApp : Application, IXamlMetadataProvider 6 | { 7 | public WinUIApp() 8 | { 9 | UnhandledException += (s, e) => 10 | { 11 | e.Handled = true; 12 | Console.WriteLine($"Unhandled Expection: {e.Exception}\nStackTrace: {e.Exception.StackTrace}"); 13 | }; 14 | } 15 | 16 | readonly XamlControlsXamlMetaDataProvider _metadataProvider = new(); 17 | 18 | public IXamlType GetXamlType(Type type) 19 | => _metadataProvider.GetXamlType(type); 20 | 21 | public IXamlType GetXamlType(string fullName) 22 | => _metadataProvider.GetXamlType(fullName); 23 | 24 | public XmlnsDefinition[] GetXmlnsDefinitions() 25 | => _metadataProvider.GetXmlnsDefinitions(); 26 | } 27 | -------------------------------------------------------------------------------- /ShortDev.Uwp.Node/XamlHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml.Markup; 2 | using ShortDev.Uwp.FullTrust.Xaml; 3 | using System.Runtime.CompilerServices; 4 | using Windows.UI.Xaml.Media; 5 | using WinRT; 6 | 7 | namespace ShortDev.Uwp.Node; 8 | 9 | /// 10 | /// Helper to interact with WinRT and Xaml apis 11 | /// 12 | [JSExport] 13 | public static partial class XamlHelper 14 | { 15 | static Application? _app; 16 | 17 | static ReflectionXamlMetadataProvider _metadataProvider = null!; 18 | static IXamlType GetXamlType(string typeName, string? typeNamespace) 19 | { 20 | IXamlType? xamlType = null; 21 | if (!string.IsNullOrEmpty(typeNamespace)) 22 | xamlType = _metadataProvider.GetXamlType($"{typeNamespace}.{typeName}"); 23 | else 24 | xamlType = _app.As().GetXamlType($"Microsoft.UI.Xaml.Controls.{typeName}"); 25 | 26 | xamlType ??= _metadataProvider.GetXamlType($"Windows.UI.Xaml.Controls.{typeName}"); 27 | 28 | if (xamlType is not null) 29 | return xamlType; 30 | 31 | throw new InvalidOperationException($"Type \"{typeName}\" could not be found"); 32 | } 33 | static IXamlMember GetXamlMember(object obj, string propertyName) 34 | { 35 | var xamlType = _metadataProvider.GetXamlType(obj.GetType()) ?? throw new InvalidOperationException($"Invalid type {obj.GetType()}"); 36 | return xamlType.GetMember(propertyName) ?? throw new ArgumentException($"Invalid member {propertyName}", nameof(propertyName)); 37 | } 38 | 39 | /// 40 | /// Initializes the WinUI App singleton 41 | /// 42 | public static async Task InitializeAsync() 43 | { 44 | if (_app is not null) 45 | return; 46 | 47 | //var files = await Task.WhenAll( 48 | // Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.pri") 49 | // .Select(async path => await StorageFile.GetFileFromPathAsync(path)) 50 | //); 51 | //ResourceManager.Current.LoadPriFiles(files); 52 | 53 | _metadataProvider = new(); 54 | _app = new WinUIApp(); 55 | 56 | var window = XamlWindowFactory.CreateNewWindow(new("Node.js")); 57 | window.Content = new Frame(); 58 | window.Activate(); 59 | 60 | // _app.Resources = new Microsoft.UI.Xaml.Controls.XamlControlsResources(); 61 | } 62 | 63 | /// 64 | /// Get the root element 65 | /// 66 | /// 67 | public static object GetRootElement() 68 | => Window.Current.Content; 69 | 70 | /// 71 | /// Creates a xaml element 72 | /// 73 | /// tag-name 74 | /// Optionally the namespace of the type 75 | /// 76 | /// If the type could not be found 77 | public static object CreateElement(string typeName, string? typeNamespace) 78 | { 79 | ArgumentNullException.ThrowIfNull(typeName); 80 | 81 | return GetXamlType(typeName, typeNamespace).ActivateInstance(); 82 | } 83 | 84 | /// 85 | /// Get value of a property 86 | /// 87 | /// 88 | /// 89 | /// 90 | /// 91 | /// 92 | public static object GetValue(object obj, string propertyName) 93 | { 94 | ArgumentNullException.ThrowIfNull(obj); 95 | ArgumentNullException.ThrowIfNull(propertyName); 96 | 97 | return GetXamlMember(obj, propertyName).GetValue(obj); 98 | } 99 | 100 | /// 101 | /// Set value of a property 102 | /// 103 | /// 104 | /// 105 | /// 106 | public static void SetValue(object obj, string propertyName, object? value) 107 | { 108 | ArgumentNullException.ThrowIfNull(propertyName); 109 | ArgumentNullException.ThrowIfNull(value); 110 | 111 | var member = GetXamlMember(obj, propertyName); 112 | member.SetValue(obj, 113 | XamlBindingHelper.ConvertValue(member.Type.UnderlyingType, value) 114 | ); 115 | } 116 | 117 | static readonly ConditionalWeakTable> _handlers = []; 118 | 119 | /// 120 | /// Add event handler 121 | /// 122 | /// 123 | /// 124 | /// 125 | public static void SetEventHandler(object obj, string eventName, Action handler) 126 | { 127 | ArgumentNullException.ThrowIfNull(obj); 128 | ArgumentNullException.ThrowIfNull(eventName); 129 | 130 | var type = obj.GetType(); 131 | var @event = type.GetEvent(eventName) ?? throw new ArgumentException($"No event {eventName} on type {type.Name}"); 132 | 133 | var handlerMap = _handlers.GetOrCreateValue(obj); 134 | if (handlerMap.TryGetValue(eventName, out var oldHandler)) 135 | @event.RemoveEventHandler(obj, oldHandler); 136 | 137 | RoutedEventHandler newHandler = (sender, args) => handler(sender); 138 | @event.AddEventHandler(obj, newHandler); 139 | handlerMap[eventName] = newHandler; 140 | } 141 | 142 | /// 143 | /// Get parent element 144 | /// 145 | /// 146 | /// 147 | public static object? GetParent(object child) 148 | { 149 | ArgumentNullException.ThrowIfNull(child); 150 | 151 | return VisualTreeHelper.GetParent((DependencyObject)child); 152 | } 153 | 154 | /// 155 | /// Get the next sibling 156 | /// 157 | /// 158 | /// 159 | /// 160 | public static object? GetNextSibling(object child) 161 | { 162 | ArgumentNullException.ThrowIfNull(child); 163 | 164 | var childElement = (UIElement)child; 165 | if (VisualTreeHelper.GetParent(childElement) is not Panel panel) 166 | throw new InvalidOperationException("Cannot get children from non-panel parent"); 167 | 168 | var newIndex = panel.Children.IndexOf(childElement) + 1; 169 | if (newIndex >= panel.Children.Count) 170 | return null; 171 | 172 | return panel.Children[newIndex]; 173 | } 174 | 175 | /// 176 | /// Add element as child of another element 177 | /// 178 | /// 179 | /// 180 | /// 181 | /// 182 | public static void InsertChild(object child, object parent, object? anchor) 183 | { 184 | ArgumentNullException.ThrowIfNull(child); 185 | ArgumentNullException.ThrowIfNull(parent); 186 | 187 | if (parent is ContentControl contentControl) 188 | { 189 | contentControl.Content = child; 190 | return; 191 | } 192 | 193 | var childElement = (UIElement)child; 194 | if (parent is Panel panel) 195 | { 196 | if (anchor is not UIElement anchorElement) 197 | { 198 | panel.Children.Add(childElement); 199 | return; 200 | } 201 | 202 | var insertionIndex = panel.Children.IndexOf(anchorElement); 203 | panel.Children.Insert(insertionIndex, childElement); 204 | return; 205 | } 206 | 207 | throw new InvalidOperationException($"Cannot add Child to {parent.GetType().Name}"); 208 | } 209 | 210 | /// 211 | /// Removes an element from the visual tree 212 | /// 213 | /// 214 | public static void RemoveChild(object child) 215 | { 216 | ArgumentNullException.ThrowIfNull(child); 217 | 218 | var childElement = (UIElement)child; 219 | if (VisualTreeHelper.GetParent(childElement) is not Panel panel) 220 | throw new InvalidOperationException("Cannot remove child from non-panel parent"); 221 | 222 | panel.Children.Remove(childElement); 223 | } 224 | 225 | /// 226 | /// Processes all current events in the message loop 227 | /// 228 | public static void ProcessEvents() 229 | { 230 | Window.Current.Dispatcher.ProcessEvents(Windows.UI.Core.CoreProcessEventsOption.ProcessOneIfPresent); 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /ShortDev.Win32/Composition/DwmApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace ShortDev.Win32.Composition; 5 | 6 | public static partial class DesktopWindowManager 7 | { 8 | public static void SetWindowAttribute(IntPtr hwnd, DwmWindowAttribute attr, bool value) 9 | => Marshal.ThrowExceptionForHR(SetWindowAttributeInternal(hwnd, attr, ref value, Marshal.SizeOf())); 10 | 11 | public static void SetWindowAttribute(IntPtr hwnd, DwmWindowAttribute attr, int value) 12 | => Marshal.ThrowExceptionForHR(SetWindowAttributeInternal(hwnd, attr, ref value, Marshal.SizeOf())); 13 | 14 | [LibraryImport("dwmapi.dll", EntryPoint = "DwmSetWindowAttribute")] 15 | internal static partial int SetWindowAttributeInternal(IntPtr hwnd, DwmWindowAttribute attr, ref int attrValue, int attrSize); 16 | 17 | [LibraryImport("dwmapi.dll", EntryPoint = "DwmSetWindowAttribute")] 18 | internal static partial int SetWindowAttributeInternal(IntPtr hwnd, DwmWindowAttribute attr, [MarshalAs(UnmanagedType.Bool)] ref bool attrValue, int attrSize); 19 | 20 | 21 | [LibraryImport("dwmapi.dll", EntryPoint = "DwmGetWindowAttribute")] 22 | internal static partial int GetWindowAttributeInternal(IntPtr hwnd, DwmWindowAttribute attr, out int attrValue, int attrSize); 23 | } 24 | 25 | public enum DwmWindowAttribute 26 | { 27 | NCRENDERING_ENABLED = 1, 28 | NCRENDERING_POLICY, 29 | TRANSITIONS_FORCEDISABLED, 30 | ALLOW_NCPAINT, 31 | CAPTION_BUTTON_BOUNDS, 32 | NONCLIENT_RTL_LAYOUT, 33 | FORCE_ICONIC_REPRESENTATION, 34 | FLIP3D_POLICY, 35 | EXTENDED_FRAME_BOUNDS, 36 | HAS_ICONIC_BITMAP, 37 | DISALLOW_PEEK, 38 | EXCLUDED_FROM_PEEK, 39 | CLOAK, 40 | CLOAKED, 41 | FREEZE_REPRESENTATION, 42 | PASSIVE_UPDATE_MODE, 43 | USE_HOSTBACKDROPBRUSH, 44 | USE_IMMERSIVE_DARK_MODE = 20, 45 | WINDOW_CORNER_PREFERENCE = 33, 46 | BORDER_COLOR, 47 | CAPTION_COLOR, 48 | TEXT_COLOR, 49 | VISIBLE_FRAME_BORDER_THICKNESS, 50 | SYSTEMBACKDROP_TYPE, 51 | LAST 52 | } 53 | -------------------------------------------------------------------------------- /ShortDev.Win32/Composition/WindowCompositionHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace ShortDev.Win32.Composition; 5 | 6 | public static partial class WindowCompositionHelper 7 | { 8 | [LibraryImport("user32.dll")] 9 | public static partial int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttribData data); 10 | } 11 | 12 | [StructLayout(LayoutKind.Sequential)] 13 | public unsafe struct WindowCompositionAttribData 14 | { 15 | public WindowCompositionAttrib Attrib; 16 | public void* pvData; 17 | public uint cbData; 18 | } 19 | 20 | public enum WindowCompositionAttrib : int 21 | { 22 | UNDEFINED = 0x0, 23 | NCRENDERING_ENABLED = 0x1, 24 | NCRENDERING_POLICY = 0x2, 25 | TRANSITIONS_FORCEDISABLED = 0x3, 26 | ALLOW_NCPAINT = 0x4, 27 | CAPTION_BUTTON_BOUNDS = 0x5, 28 | NONCLIENT_RTL_LAYOUT = 0x6, 29 | FORCE_ICONIC_REPRESENTATION = 0x7, 30 | EXTENDED_FRAME_BOUNDS = 0x8, 31 | HAS_ICONIC_BITMAP = 0x9, 32 | THEME_ATTRIBUTES = 0xA, 33 | NCRENDERING_EXILED = 0xB, 34 | NCADORNMENTINFO = 0xC, 35 | EXCLUDED_FROM_LIVEPREVIEW = 0xD, 36 | VIDEO_OVERLAY_ACTIVE = 0xE, 37 | FORCE_ACTIVEWINDOW_APPEARANCE = 0xF, 38 | DISALLOW_PEEK = 0x10, 39 | CLOAK = 0x11, 40 | CLOAKED = 0x12, 41 | ACCENT_POLICY = 0x13, 42 | FREEZE_REPRESENTATION = 0x14, 43 | EVER_UNCLOAKED = 0x15, 44 | VISUAL_OWNER = 0x16, 45 | HOLOGRAPHIC = 0x17, 46 | EXCLUDED_FROM_DDA = 0x18, 47 | PASSIVEUPDATEMODE = 0x19, 48 | USEDARKMODECOLORS = 0x1A, 49 | LAST = 0x1B, 50 | } 51 | 52 | [StructLayout(LayoutKind.Sequential)] 53 | public struct AccentPolicy 54 | { 55 | public AccentState AccentState; 56 | public uint AccentFlags; 57 | public uint GradientColor; 58 | public int AnimationId; 59 | } 60 | 61 | public enum AccentState : int 62 | { 63 | DISABLED = 0x0, 64 | ENABLE_GRADIENT = 0x1, 65 | ENABLE_TRANSPARENTGRADIENT = 0x2, 66 | ENABLE_BLURBEHIND = 0x3, 67 | ENABLE_ACRYLICBLURBEHIND = 0x4, 68 | ENABLE_HOSTBACKDROP = 0x5, 69 | INVALID_STATE = 0x6, 70 | }; 71 | -------------------------------------------------------------------------------- /ShortDev.Win32/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using static Windows.Win32.PInvoke; 2 | global using XamlWindow = Windows.UI.Xaml.Window; 3 | -------------------------------------------------------------------------------- /ShortDev.Win32/NativeMethods.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://aka.ms/CsWin32.schema.json", 3 | "useSafeHandles": false, 4 | "allowMarshaling": true 5 | } -------------------------------------------------------------------------------- /ShortDev.Win32/NativeMethods.txt: -------------------------------------------------------------------------------- 1 | SetWindowSubclass 2 | RemoveWindowSubclass 3 | DefSubclassProc 4 | DefWindowProc 5 | DwmDefWindowProc 6 | 7 | DwmExtendFrameIntoClientArea 8 | SetWindowTheme 9 | 10 | NCCALCSIZE_PARAMS 11 | SendMessage 12 | ReleaseCapture 13 | EnableMouseInPointer 14 | WM_NCLBUTTONDOWN 15 | ScreenToClient 16 | GetDpiForWindow 17 | 18 | RegisterClassEx 19 | CreateWindowEx 20 | GetWindowRect 21 | DestroyWindow 22 | 23 | SetForegroundWindow 24 | SetWindowPos 25 | SetWindowLong 26 | GetWindowLong 27 | ShowWindow 28 | PostMessage 29 | 30 | WM_CLOSE 31 | WM_DESTROY 32 | WM_NCCALCSIZE 33 | WM_NCHITTEST 34 | WM_ACTIVATE 35 | 36 | LoadLibraryExW 37 | FreeLibrary 38 | 39 | CreateDispatcherQueueController 40 | 41 | RoGetActivationFactory 42 | CoCreateInstance 43 | WindowsCreateStringReference 44 | 45 | ICoreWindowInterop 46 | GetTokenInformation 47 | GetCurrentPackageFullName -------------------------------------------------------------------------------- /ShortDev.Win32/ShortDev.Win32.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0-windows10.0.22621.0 5 | 6 | 7 | 8 | 9 | all 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ShortDev.Win32/Windowing/Window.cs: -------------------------------------------------------------------------------- 1 | using ShortDev.Win32.Composition; 2 | using System; 3 | using System.ComponentModel; 4 | using System.Runtime.InteropServices; 5 | using Windows.UI.Composition; 6 | using Windows.Win32.Foundation; 7 | using Windows.Win32.UI.WindowsAndMessaging; 8 | 9 | namespace ShortDev.Win32.Windowing; 10 | 11 | public sealed class Window 12 | { 13 | private Window() { } 14 | 15 | public nint Hwnd { get; private set; } 16 | 17 | public static Window FromHwnd(nint hwnd) 18 | => new() 19 | { 20 | Hwnd = hwnd 21 | }; 22 | 23 | internal void NotifyFrameChanged() 24 | { 25 | // https://github.com/strobejb/winspy/blob/03887c8ab1ebc9abad6865743eba15b94c9e9dbc/src/StyleEdit.c#L143 26 | SetWindowPos( 27 | (HWND)Hwnd, HWND.Null, 28 | 0, 0, 0, 0, 29 | SET_WINDOW_POS_FLAGS.SWP_NOMOVE | SET_WINDOW_POS_FLAGS.SWP_NOSIZE | SET_WINDOW_POS_FLAGS.SWP_NOZORDER | SET_WINDOW_POS_FLAGS.SWP_NOACTIVATE | SET_WINDOW_POS_FLAGS.SWP_FRAMECHANGED 30 | ); 31 | } 32 | 33 | #region Win32 Frame 34 | bool _minimizeBox = true; 35 | public bool MinimizeBox 36 | { 37 | get => _minimizeBox; 38 | set 39 | { 40 | if (value == _minimizeBox) 41 | return; 42 | 43 | _minimizeBox = value; 44 | UpdateFrameFlags(); 45 | } 46 | } 47 | 48 | bool _maximizeBox = true; 49 | public bool MaximizeBox 50 | { 51 | get => _maximizeBox; 52 | set 53 | { 54 | if (value == _maximizeBox) 55 | return; 56 | 57 | _maximizeBox = value; 58 | UpdateFrameFlags(); 59 | } 60 | } 61 | 62 | bool _hasWin32Frame = false; 63 | public bool HasWin32Frame 64 | { 65 | get => _hasWin32Frame; 66 | set 67 | { 68 | if (value == _hasWin32Frame) 69 | return; 70 | 71 | _hasWin32Frame = value; 72 | UpdateFrameFlags(); 73 | } 74 | } 75 | 76 | void UpdateFrameFlags() 77 | { 78 | var flags = GetWindowLong((HWND)Hwnd, WINDOW_LONG_PTR_INDEX.GWL_STYLE); 79 | if (HasWin32Frame) 80 | { 81 | flags |= (int)WINDOW_STYLE.WS_THICKFRAME; 82 | flags |= (int)WINDOW_STYLE.WS_SYSMENU; 83 | flags |= (int)WINDOW_STYLE.WS_DLGFRAME; 84 | flags |= (int)WINDOW_STYLE.WS_BORDER; 85 | 86 | if (MinimizeBox) 87 | flags |= (int)WINDOW_STYLE.WS_MINIMIZEBOX; 88 | if (MaximizeBox) 89 | flags |= (int)WINDOW_STYLE.WS_MAXIMIZEBOX; 90 | } 91 | else 92 | { 93 | flags &= ~(int)WINDOW_STYLE.WS_THICKFRAME; 94 | flags &= ~(int)WINDOW_STYLE.WS_SYSMENU; 95 | flags &= ~(int)WINDOW_STYLE.WS_DLGFRAME; 96 | flags &= ~(int)WINDOW_STYLE.WS_BORDER; 97 | 98 | flags &= ~(int)WINDOW_STYLE.WS_MINIMIZEBOX; 99 | flags &= ~(int)WINDOW_STYLE.WS_MAXIMIZEBOX; 100 | } 101 | SetWindowLong((HWND)Hwnd, WINDOW_LONG_PTR_INDEX.GWL_STYLE, flags); 102 | NotifyFrameChanged(); 103 | } 104 | #endregion 105 | 106 | #region TopMost 107 | bool _isTopMost = false; 108 | public bool IsTopMost 109 | { 110 | get => _isTopMost; 111 | set 112 | { 113 | // ToDo: This activates the window... 114 | //if (value == _isTopMost) 115 | // return; 116 | 117 | const int HWND_TOPMOST = -1; 118 | const int HWND_NOTOPMOST = -2; 119 | SetWindowPos((HWND)Hwnd, 120 | value ? (HWND)HWND_TOPMOST : (HWND)HWND_NOTOPMOST, 121 | 0, 0, 0, 0, 122 | SET_WINDOW_POS_FLAGS.SWP_NOMOVE | SET_WINDOW_POS_FLAGS.SWP_NOSIZE 123 | ); 124 | _isTopMost = value; 125 | } 126 | } 127 | #endregion 128 | 129 | #region ShowInTaskBar 130 | bool _showInTaskBar = true; 131 | public bool ShowInTaskBar 132 | { 133 | get => _showInTaskBar; 134 | set 135 | { 136 | if (value == _showInTaskBar) 137 | return; 138 | 139 | var flags = GetWindowLong((HWND)Hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE); 140 | if (!value) 141 | flags |= (int)WINDOW_EX_STYLE.WS_EX_TOOLWINDOW; 142 | else 143 | flags &= ~(int)WINDOW_EX_STYLE.WS_EX_TOOLWINDOW; 144 | SetWindowLong((HWND)Hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, flags); 145 | NotifyFrameChanged(); 146 | _showInTaskBar = value; 147 | } 148 | } 149 | #endregion 150 | 151 | #region Dark Mode 152 | bool _useDarkMode = false; 153 | public bool UseDarkMode 154 | { 155 | get => _useDarkMode; 156 | set 157 | { 158 | // https://github.com/qt/qtbase/blob/1808df9ce59a8c1d426f0361e25120a7852a6442/src/plugins/platforms/windows/qwindowswindow.cpp#L3168 159 | int hRes = DesktopWindowManager.SetWindowAttributeInternal(Hwnd, (DwmWindowAttribute)19, ref value, sizeof(int)); 160 | if (hRes != 0) 161 | Marshal.ThrowExceptionForHR(DesktopWindowManager.SetWindowAttributeInternal(Hwnd, (DwmWindowAttribute)20, ref value, sizeof(int))); 162 | NotifyFrameChanged(); 163 | _useDarkMode = value; 164 | } 165 | } 166 | #endregion 167 | 168 | /// 169 | /// Enables the HostBackdrop brush for acrylic 170 | /// 171 | public unsafe void EnableHostBackdropBrush() 172 | { 173 | // Windows.UI.Xaml.dll!DirectUI::Window::EnableHostBackdropBrush 174 | WindowCompositionAttribData dwAttribute; 175 | dwAttribute.Attrib = WindowCompositionAttrib.ACCENT_POLICY; 176 | AccentPolicy policy; 177 | policy.AccentState = AccentState.ENABLE_HOSTBACKDROP; 178 | dwAttribute.pvData = &policy; 179 | dwAttribute.cbData = (uint)Marshal.SizeOf(policy); 180 | WindowCompositionHelper.SetWindowCompositionAttribute(Hwnd, ref dwAttribute); 181 | } 182 | 183 | /// 184 | /// Gets or sets wether the window is drawn.
185 | /// See 186 | ///
187 | public bool IsCloaked 188 | { 189 | get 190 | { 191 | Marshal.ThrowExceptionForHR(DesktopWindowManager.GetWindowAttributeInternal( 192 | Hwnd, 193 | DwmWindowAttribute.CLOAKED, 194 | out var value, 195 | sizeof(int) 196 | )); 197 | return value != 0; 198 | } 199 | set 200 | { 201 | Marshal.ThrowExceptionForHR(DesktopWindowManager.SetWindowAttributeInternal( 202 | Hwnd, 203 | DwmWindowAttribute.CLOAK, 204 | ref value, 205 | sizeof(int) 206 | )); 207 | } 208 | } 209 | 210 | public void BringToFront() 211 | { 212 | if (!SetForegroundWindow((HWND)Hwnd)) 213 | throw new Win32Exception(); 214 | } 215 | 216 | void ShowWindowInternal(SHOW_WINDOW_CMD cmd) 217 | { 218 | if (!ShowWindow((HWND)Hwnd, cmd)) 219 | throw new Win32Exception(); 220 | } 221 | 222 | public void Show() 223 | => ShowWindowInternal(SHOW_WINDOW_CMD.SW_SHOW); 224 | 225 | public void Hide() 226 | => ShowWindowInternal(SHOW_WINDOW_CMD.SW_HIDE); 227 | } 228 | -------------------------------------------------------------------------------- /ShortDev.Win32/Windowing/WindowCloseRequestedEventArgs.cs: -------------------------------------------------------------------------------- 1 | using Windows.Foundation; 2 | using Windows.Win32.Foundation; 3 | 4 | namespace ShortDev.Win32.Windowing; 5 | 6 | public sealed class WindowCloseRequestedEventArgs 7 | { 8 | readonly WindowSubclass _subclass; 9 | public WindowCloseRequestedEventArgs(WindowSubclass subclass) 10 | => _subclass = subclass; 11 | 12 | internal bool IsDeferred { get; private set; } = false; 13 | 14 | /// 15 | /// A object for the CloseRequested event. 16 | /// 17 | public Deferral GetDeferral() 18 | { 19 | IsDeferred = true; 20 | return new(() => 21 | { 22 | IsDeferred = false; 23 | PostMessage((HWND)_subclass.Hwnd, WM_CLOSE, 0, 0); 24 | }); 25 | } 26 | 27 | /// 28 | /// Gets or sets a value that indicates whether the close request is handled by the app.
29 | /// if the app has handled the close request; otherwise, . The default is . 30 | ///
31 | public bool Handled { get; set; } = false; 32 | } 33 | -------------------------------------------------------------------------------- /ShortDev.Win32/Windowing/WindowSubclass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Runtime.InteropServices; 7 | using Windows.Foundation; 8 | using Windows.UI.Xaml; 9 | using Windows.UI.Xaml.Media; 10 | using Windows.Win32.Foundation; 11 | using Windows.Win32.UI.Controls; 12 | using Windows.Win32.UI.Shell; 13 | using Windows.Win32.UI.WindowsAndMessaging; 14 | 15 | namespace ShortDev.Win32.Windowing; 16 | 17 | public sealed class WindowSubclass 18 | { 19 | #region Singleton 20 | static readonly ConcurrentDictionary _subclassRegistry = new(); 21 | 22 | /// 23 | /// Attaches a to a given hwnd.
24 | /// Only one subclass ist allowed per window! 25 | ///
26 | /// 27 | /// 28 | public static WindowSubclass Attach(nint hWnd, bool throwIfExists = true) 29 | { 30 | if (_subclassRegistry.TryGetValue(hWnd, out var subclass)) 31 | { 32 | if (throwIfExists) 33 | throw new ArgumentException($"Window already has a subclass!"); 34 | 35 | return subclass; 36 | } 37 | 38 | subclass = new(hWnd); 39 | subclass.Install(); 40 | 41 | var added = _subclassRegistry.TryAdd(hWnd, subclass); 42 | Debug.Assert(added); 43 | 44 | return subclass; 45 | } 46 | #endregion 47 | 48 | #region Instance 49 | public nint Hwnd { get; } 50 | public Window Win32Window { get; private set; } 51 | 52 | private WindowSubclass(nint hwnd) 53 | { 54 | Hwnd = hwnd; 55 | Win32Window = Window.FromHwnd(hwnd); 56 | } 57 | 58 | void OnDestroy() 59 | { 60 | try 61 | { 62 | Uninstall(); 63 | _subclassRegistry.TryRemove(Hwnd, out _); 64 | } 65 | catch { } 66 | } 67 | #endregion 68 | 69 | #region Subclass Installation 70 | SUBCLASSPROC? _subclassProc; 71 | nint? _subclassProcPtr; 72 | void Install() 73 | { 74 | if (_subclassProc != null) 75 | throw new InvalidOperationException(); 76 | 77 | _subclassProc = XamlWindowSubclassProc; 78 | _subclassProcPtr = Marshal.GetFunctionPointerForDelegate(_subclassProc); 79 | SetWindowSubclass((HWND)Hwnd, _subclassProc, 0, 0); 80 | } 81 | 82 | void Uninstall() 83 | { 84 | if (_subclassProc == null) 85 | throw new InvalidOperationException(); 86 | 87 | RemoveWindowSubclass((HWND)Hwnd, _subclassProc, 0); 88 | _subclassProc = null; 89 | } 90 | #endregion 91 | 92 | unsafe LRESULT XamlWindowSubclassProc(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam, nuint id, nuint data) 93 | { 94 | foreach (var filter in Filters) 95 | { 96 | if (filter.PreFilterMessage(hwnd, (int)msg, wParam, lParam, id, out var result)) 97 | return (LRESULT)result; 98 | } 99 | 100 | if (ExtendsContentIntoTitleBar && DwmDefWindowProc(hwnd, msg, wParam, lParam, out var dwmResult)) 101 | return dwmResult; 102 | 103 | if (msg == WM_ACTIVATE) 104 | { 105 | MARGINS margins = new() 106 | { 107 | cxLeftWidth = 0, 108 | cxRightWidth = 0, 109 | cyBottomHeight = 0, 110 | cyTopHeight = -1 111 | }; 112 | DwmExtendFrameIntoClientArea(hwnd, margins); 113 | // SetWindowTheme(hwnd, "", ""); 114 | } 115 | 116 | if (msg == WM_NCHITTEST) 117 | { 118 | if (IsPointInTitleBar(GetClientCoord(lParam))) 119 | return (LRESULT)2; 120 | // return (IntPtr)(-1); // Nowhere 121 | } 122 | 123 | if (!HasWin32TitleBar && msg == WM_NCCALCSIZE) 124 | { 125 | // https//github.com/microsoft/terminal/blob/ff8fdbd2431f1cfd8211833815be481dfdec4420/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp#L405 126 | var nccspOld = (NCCALCSIZE_PARAMS*)(nint)lParam; 127 | var topOld = nccspOld->rgrc._0.top; 128 | 129 | // Run default processing 130 | var result = DefSubclassProc(hwnd, msg, wParam, lParam); 131 | 132 | var nccsp = (NCCALCSIZE_PARAMS*)(nint)lParam; 133 | // Rest to old top (remove title bar) 134 | nccsp->rgrc._0.top = topOld; 135 | return result; 136 | } 137 | 138 | // https://docs.microsoft.com/en-us/windows/win32/learnwin32/closing-the-window 139 | if (msg == WM_CLOSE) 140 | { 141 | if (CloseRequested != null) 142 | { 143 | const int CANCEL = 0; 144 | if (_currentCloseRequest == null) 145 | { 146 | _currentCloseRequest = new(this); 147 | CloseRequested.Invoke(this, _currentCloseRequest); 148 | } 149 | 150 | if (_currentCloseRequest.IsDeferred) // User clicked "Close" again 151 | return (LRESULT)CANCEL; // Still waiting for user choise 152 | 153 | // Deferral of "XamlWindowCloseRequestedEventArgs" will call "Close" again 154 | if (_currentCloseRequest.Handled) 155 | { 156 | _currentCloseRequest = null; // Allow for event to be resent 157 | return (LRESULT)CANCEL; // User chose to cancel "Close" 158 | } 159 | } 160 | 161 | OnDestroy(); 162 | } 163 | 164 | return DefSubclassProc(hwnd, msg, wParam, lParam); 165 | } 166 | 167 | public bool ExtendsContentIntoTitleBar { get; set; } = true; 168 | 169 | #region Win32 TitleBar 170 | bool _hasWin32TitleBar = true; 171 | /// 172 | /// If , the window will have no (win32) titlebar 173 | /// 174 | public bool HasWin32TitleBar 175 | { 176 | get => _hasWin32TitleBar; 177 | set 178 | { 179 | _hasWin32TitleBar = value; 180 | Win32Window.NotifyFrameChanged(); 181 | } 182 | } 183 | #endregion 184 | 185 | #region TitleBar 186 | UIElement? _titleBarElement; 187 | public void SetTitleBar(UIElement? value) 188 | => _titleBarElement = value; 189 | 190 | bool IsPointInTitleBar(Point p) 191 | { 192 | if (_titleBarElement?.XamlRoot == null || p.X < 0 || p.Y < 0) 193 | return false; 194 | 195 | var ele = VisualTreeHelper.FindElementsInHostCoordinates(p, _titleBarElement.XamlRoot.Content, false).FirstOrDefault(); 196 | return ele == _titleBarElement; 197 | } 198 | 199 | Point GetClientCoord(LPARAM lParam) 200 | { 201 | int x = unchecked((short)lParam); 202 | int y = unchecked((short)((int)lParam >> 16)); 203 | System.Drawing.Point point = new(x, y); 204 | ScreenToClient((HWND)Hwnd, ref point); 205 | double scale = GetDpiForWindow((HWND)Hwnd) / 96.0; 206 | return new(point.X / scale, point.Y / scale); 207 | } 208 | #endregion 209 | 210 | #region CloseRequested 211 | WindowCloseRequestedEventArgs? _currentCloseRequest; 212 | 213 | /// 214 | /// Occurs when the user invokes the system button for close (the 'x' button in the corner of the app's title bar). 215 | /// 216 | public event EventHandler? CloseRequested; 217 | #endregion 218 | 219 | #region MessageFilter 220 | public List Filters = new(); 221 | 222 | /// 223 | /// Filters out a window message. 224 | /// 225 | public interface IMessageFilter 226 | { 227 | /// 228 | /// Filters out a message.
229 | /// to filter the message; to pass the message to the next filter or the . 230 | ///
231 | bool PreFilterMessage(nint hwnd, int msg, nuint wParam, nint lParam, nuint id, out nint result); 232 | } 233 | #endregion 234 | } 235 | --------------------------------------------------------------------------------