├── WinformsSandbox ├── Resources │ ├── WinformsSandbox.ico │ ├── Resources.Designer.cs │ └── Resources.resx ├── Properties │ ├── AssemblyVersionInfo.cs │ ├── AssemblyInfo.cs │ └── PublishProfiles │ │ └── FolderProfile.pubxml ├── Program.cs ├── Main.Designer.cs ├── WinformsSandbox.csproj ├── Main.resx └── Main.cs ├── README.md ├── WinformsSandbox.sln ├── LICENSE └── .gitignore /WinformsSandbox/Resources/WinformsSandbox.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smourier/WinformsSandbox/HEAD/WinformsSandbox/Resources/WinformsSandbox.ico -------------------------------------------------------------------------------- /WinformsSandbox/Properties/AssemblyVersionInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | [assembly: AssemblyVersion("1.0.0.0")] 4 | [assembly: AssemblyFileVersion("1.0.0.0")] 5 | [assembly: AssemblyInformationalVersion("1.0.0.0")] 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .NET Windows (Forms) Sandbox 2 | A sample Windows Forms .NET app that hosts the real and only Windows Sandbox: 3 | 4 | ![image](https://github.com/user-attachments/assets/239842d2-aa1f-4071-a562-ec51dd1b9ea7) 5 | 6 | Note: it uses partially undocumented API and I think it only works starting with Windows 11 24H2. 7 | -------------------------------------------------------------------------------- /WinformsSandbox/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Windows.Forms; 3 | 4 | namespace WinformsSandbox; 5 | 6 | internal static class Program 7 | { 8 | [STAThread] 9 | static void Main() 10 | { 11 | ApplicationConfiguration.Initialize(); 12 | Application.Run(new Main()); 13 | } 14 | } -------------------------------------------------------------------------------- /WinformsSandbox/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | using System.Runtime.Versioning; 4 | 5 | #if DEBUG 6 | [assembly: AssemblyConfiguration("DEBUG")] 7 | #else 8 | [assembly: AssemblyConfiguration("RELEASE")] 9 | #endif 10 | 11 | [assembly: AssemblyTitle("WinformsSandbox")] 12 | [assembly: AssemblyProduct("Winforms Sandbox")] 13 | [assembly: AssemblyCopyright("Copyright (C) 2024-2025 Simon Mourier. All rights reserved.")] 14 | [assembly: AssemblyCulture("")] 15 | [assembly: AssemblyDescription("Windows Sandbox Programmatically used from .NET Core Windows Forms")] 16 | [assembly: AssemblyCompany("Simon Mourier")] 17 | [assembly: Guid("5e7241c5-7b1a-4dc7-9330-2ac8987a852b")] 18 | [assembly: SupportedOSPlatform("windows10.0.19041.0")] 19 | -------------------------------------------------------------------------------- /WinformsSandbox/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Release 6 | Any CPU 7 | bin\Release\net9.0-windows10.0.19041.0\publish\win-x64\ 8 | FileSystem 9 | <_TargetId>Folder 10 | net9.0-windows10.0.19041.0 11 | win-x64 12 | true 13 | true 14 | true 15 | false 16 | true 17 | 18 | -------------------------------------------------------------------------------- /WinformsSandbox.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35527.113 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinformsSandbox", "WinformsSandbox\WinformsSandbox.csproj", "{2C237B11-5187-4BCD-9F30-7038F5192E8C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2C237B11-5187-4BCD-9F30-7038F5192E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2C237B11-5187-4BCD-9F30-7038F5192E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2C237B11-5187-4BCD-9F30-7038F5192E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2C237B11-5187-4BCD-9F30-7038F5192E8C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024-2025 Simon Mourier 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 | -------------------------------------------------------------------------------- /WinformsSandbox/Main.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace WinformsSandbox 2 | { 3 | partial class Main 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | #region Windows Form Designer generated code 11 | 12 | /// 13 | /// Required method for Designer support - do not modify 14 | /// the contents of this method with the code editor. 15 | /// 16 | private void InitializeComponent() 17 | { 18 | SuspendLayout(); 19 | // 20 | // Main 21 | // 22 | AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); 23 | AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 24 | ClientSize = new System.Drawing.Size(1200, 751); 25 | Name = "Main"; 26 | StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; 27 | Text = "Winforms Sandbox"; 28 | ResumeLayout(false); 29 | } 30 | 31 | #endregion 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /WinformsSandbox/WinformsSandbox.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | net9.0-windows10.0.19041.0 6 | enable 7 | true 8 | false 9 | Resources\WinformsSandbox.ico 10 | true 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | tlbimp 20 | 0 21 | 1 22 | 8c11efa1-92c3-11d1-bc1e-00c04fa31489 23 | 0 24 | false 25 | true 26 | 27 | 28 | aximp 29 | 0 30 | 1 31 | 8c11efa1-92c3-11d1-bc1e-00c04fa31489 32 | 0 33 | false 34 | 35 | 36 | 37 | 38 | 39 | True 40 | True 41 | Resources.resx 42 | 43 | 44 | 45 | 46 | 47 | ResXFileCodeGenerator 48 | Resources.Designer.cs 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /WinformsSandbox/Resources/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WinformsSandbox.Resources { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WinformsSandbox.Resources.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). 65 | /// 66 | internal static System.Drawing.Icon MainIcon { 67 | get { 68 | object obj = ResourceManager.GetObject("MainIcon", resourceCulture); 69 | return ((System.Drawing.Icon)(obj)); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /WinformsSandbox/Resources/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | text/microsoft-resx 91 | 92 | 93 | 1.3 94 | 95 | 96 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 97 | 98 | 99 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 100 | 101 | 102 | 103 | WinformsSandbox.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 104 | 105 | -------------------------------------------------------------------------------- /WinformsSandbox/Main.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /.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/main/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 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 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 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /WinformsSandbox/Main.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Runtime.InteropServices; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Windows.Forms; 9 | using MSTSCLib; 10 | using Windows.Management.Deployment; 11 | 12 | namespace WinformsSandbox; 13 | 14 | public partial class Main : Form 15 | { 16 | private ClientProxy? _grpcClient; 17 | private ConfigProxy? _sandboxConfig; 18 | private AxMSTSCLib.AxMsRdpClient8NotSafeForScripting? _rdpClient; 19 | 20 | public Main() 21 | { 22 | InitializeComponent(); 23 | Icon = Resources.Resources.MainIcon; 24 | } 25 | 26 | protected override void Dispose(bool disposing) // removed from Main.Designer.cs 27 | { 28 | if (disposing) 29 | { 30 | components?.Dispose(); 31 | if (_grpcClient != null) 32 | { 33 | if (_sandboxConfig != null) 34 | { 35 | _grpcClient.ShutdownSandbox(_sandboxConfig.SandboxId); 36 | _sandboxConfig = null; 37 | } 38 | _grpcClient.Dispose(); 39 | _grpcClient = null; 40 | } 41 | _rdpClient?.Dispose(); 42 | } 43 | base.Dispose(disposing); 44 | } 45 | 46 | protected override void CreateHandle() 47 | { 48 | base.CreateHandle(); 49 | _ = Task.Run(() => 50 | { 51 | BeginInvoke(async () => 52 | { 53 | try 54 | { 55 | GetSandboxClient(); 56 | } 57 | catch (Exception ex) 58 | { 59 | Controls.Add(new Label { Text = $"The Windows Sandbox API is not available. {ex.Message}", AutoSize = true, Padding = new Padding(10) }); 60 | return; 61 | } 62 | 63 | var connector = NamedPipeConnector.Create(); 64 | if (connector == null) 65 | { 66 | Controls.Add(new Label { Text = "The RDP API is not available.", AutoSize = true, Padding = new Padding(10) }); 67 | return; 68 | } 69 | 70 | await StartAndConnect(connector); 71 | }); 72 | }); 73 | } 74 | 75 | protected override void OnSizeChanged(EventArgs e) 76 | { 77 | base.OnSizeChanged(e); 78 | if (_rdpClient != null) 79 | { 80 | var size = ClientSize; 81 | if (_rdpClient.Connected == 1) 82 | { 83 | var ocx = (IMsRdpClient9)_rdpClient.GetOcx()!; 84 | ocx.UpdateSessionDisplaySettings((uint)size.Width, (uint)size.Height, (uint)size.Width, (uint)size.Height, 0u, 100, 100); 85 | } 86 | else 87 | { 88 | _rdpClient.DesktopHeight = size.Height; 89 | _rdpClient.DesktopWidth = size.Width; 90 | } 91 | } 92 | } 93 | 94 | private async Task StartAndConnect(NamedPipeConnector connector) 95 | { 96 | // start the sandbox 97 | _sandboxConfig = await _grpcClient!.StartSandboxAsync(); 98 | 99 | // get a named pipe endpoint 100 | var pipeName = $@"\\.\pipe\{_sandboxConfig.VMId}"; 101 | var endpoint = await connector.GetEndpoint(pipeName); 102 | 103 | // connect the RDP client 104 | _rdpClient = new AxMSTSCLib.AxMsRdpClient8NotSafeForScripting { Dock = DockStyle.Fill }; 105 | Controls.Add(_rdpClient); 106 | _rdpClient.AdvancedSettings9.EnableCredSspSupport = false; 107 | _rdpClient.AdvancedSettings9.NegotiateSecurityLayer = true; 108 | _rdpClient.UserName = _sandboxConfig.Username; 109 | _rdpClient.AdvancedSettings9.ClearTextPassword = _sandboxConfig.Password; 110 | _rdpClient.AdvancedSettings9.set_ConnectWithEndpoint(ref endpoint); 111 | _rdpClient.Connect(); 112 | } 113 | 114 | private void GetSandboxClient() 115 | { 116 | var pm = new PackageManager(); 117 | var packageName = "Windows Sandbox"; 118 | var package = pm.FindPackagesForUser(string.Empty).FirstOrDefault(p => p.DisplayName == packageName) ?? throw new Exception($"Cannot find '{packageName}' package."); 119 | var file = Path.Combine(package.InstalledPath, "SandboxCommon.dll"); 120 | if (!File.Exists(file)) 121 | throw new Exception($"Cannot find '{file}' file."); 122 | 123 | var bytes = File.ReadAllBytes(file); 124 | var asm = Assembly.Load(bytes); 125 | var typeName = "SandboxCommon.Grpc.GrpcClient"; 126 | var clientType = asm.GetType(typeName) ?? throw new Exception($"Cannot find '{typeName}' type."); 127 | 128 | // resolve all dlls from the package 129 | AppDomain.CurrentDomain.AssemblyResolve += (s, e) => 130 | { 131 | var name = e.Name.Split(',')[0] + ".dll"; 132 | var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == e.Name); 133 | if (assembly != null) 134 | return assembly; 135 | 136 | var file = Path.Combine(package.InstalledPath, name); 137 | if (File.Exists(file)) 138 | { 139 | var bytes = File.ReadAllBytes(file); 140 | var asm = Assembly.Load(bytes); 141 | return asm; 142 | } 143 | return null; 144 | }; 145 | 146 | if (Activator.CreateInstance(clientType, [null]) is not IDisposable client) 147 | throw new Exception($"Cannot find create instance of '{clientType.FullName}' type."); 148 | 149 | _grpcClient = new ClientProxy(client); 150 | } 151 | 152 | // reflection-built proxies, we could use the SandboxCommon.dll directly too. 153 | private sealed class ClientProxy(IDisposable client) : IDisposable 154 | { 155 | private IDisposable? _client = client; 156 | 157 | public void ShutdownSandbox(Guid sandboxId) 158 | { 159 | ObjectDisposedException.ThrowIf(_client == null, this); 160 | _client.GetType().InvokeMember(nameof(ShutdownSandbox), BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, _client, 161 | [sandboxId]); 162 | } 163 | 164 | public async Task StartSandboxAsync() 165 | { 166 | ObjectDisposedException.ThrowIf(_client == null, this); 167 | dynamic task = _client.GetType().InvokeMember(nameof(StartSandboxAsync), BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, _client, 168 | [string.Empty, null, null])!; 169 | try 170 | { 171 | await task; 172 | } 173 | catch (COMException ex) 174 | { 175 | const int CO_E_APPSINGLEUSE = unchecked((int)0x800401f6); 176 | if (ex.HResult == CO_E_APPSINGLEUSE) 177 | throw new Exception("Cannot start a new sandbox, the main one may be opened, or if it's not, try to kill running instances of WindowsSandboxServer.exe and ManagedWindowsVM.exe processes."); 178 | 179 | throw; 180 | } 181 | 182 | var config = task.GetAwaiter().GetResult(); 183 | return new ConfigProxy(config); 184 | } 185 | 186 | public void Dispose() => Interlocked.Exchange(ref _client, null)?.Dispose(); 187 | } 188 | 189 | private sealed class ConfigProxy 190 | { 191 | public ConfigProxy(object config) 192 | { 193 | var type = config.GetType(); 194 | SandboxId = (Guid)type.GetProperty(nameof(SandboxId))!.GetValue(config)!; 195 | VMId = (Guid)type.GetProperty(nameof(VMId))!.GetValue(config)!; 196 | Username = (string)type.GetProperty(nameof(Username))!.GetValue(config)!; 197 | Password = (string)type.GetProperty(nameof(Password))!.GetValue(config)!; 198 | } 199 | 200 | public Guid SandboxId { get; } 201 | public Guid VMId { get; } 202 | public string Username { get; } 203 | public string Password { get; } 204 | 205 | public override string ToString() => $"{SandboxId}"; 206 | } 207 | 208 | // undocumented RDP interfaces 209 | private sealed class NamedPipeConnector : NamedPipeConnector.IRDPENCNamedPipeDirectConnectorCallbacks, IDisposable 210 | { 211 | private IRDPENCNamedPipeDirectConnector? _connector; 212 | private readonly TaskCompletionSource _source; 213 | 214 | public static NamedPipeConnector? Create() 215 | { 216 | var CLSID_RDPRuntimeSTAContext = new Guid("fb332ae7-0055-4208-92b7-20410ca8382b"); 217 | _ = RDPBASE_CreateInstance(0, CLSID_RDPRuntimeSTAContext, typeof(IRDPENCPlatformContext).GUID, out var ctx); 218 | if (ctx == null) 219 | return null; 220 | 221 | var hr = ((IRDPENCPlatformContext)ctx).InitializeInstance(); 222 | if (hr < 0) 223 | return null; 224 | 225 | var CLSID_RDPENCNamedPipeDirectConnector = new Guid("fb332ae7-0088-4208-92b7-20410ca8382b"); 226 | _ = RDPBASE_CreateInstance(Marshal.GetIUnknownForObject(ctx), CLSID_RDPENCNamedPipeDirectConnector, typeof(IRDPENCNamedPipeDirectConnector).GUID, out var connector); 227 | if (connector == null) 228 | return null; 229 | 230 | return new NamedPipeConnector((IRDPENCNamedPipeDirectConnector)connector); 231 | } 232 | 233 | private NamedPipeConnector(IRDPENCNamedPipeDirectConnector connector) 234 | { 235 | _connector = connector; 236 | _source = new TaskCompletionSource(); 237 | var hr = _connector.InitializeInstance(this); 238 | if (hr < 0) 239 | { 240 | _source.SetException(Marshal.GetExceptionForHR(hr)!); 241 | } 242 | } 243 | 244 | public async Task GetEndpoint(string pipeName) 245 | { 246 | ObjectDisposedException.ThrowIf(_connector == null, this); 247 | _connector.StartConnect(pipeName); 248 | return await _source.Task; 249 | } 250 | 251 | public void OnConnectionCompleted(object stream) => _source.TrySetResult(stream); 252 | public void OnConnectorError(int hr) => _source.TrySetException(Marshal.GetExceptionForHR(hr)!); 253 | 254 | public void Dispose() 255 | { 256 | try 257 | { 258 | Interlocked.Exchange(ref _connector, null)?.TerminateInstance(); 259 | } 260 | catch 261 | { 262 | // do nothing 263 | } 264 | } 265 | 266 | [DllImport("RdpBase")] 267 | private static extern int RDPBASE_CreateInstance(nint platformContext, in Guid rclsid, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object obj); 268 | 269 | #pragma warning disable IDE0079 // Remove unnecessary suppression 270 | #pragma warning disable SYSLIB1096 // Convert to 'GeneratedComInterface' 271 | [ComImport, Guid("4ACF942D-EADC-45bf-8EA8-793FE3CE31E8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 272 | private interface IRDPENCNamedPipeDirectConnector 273 | { 274 | [PreserveSig] 275 | int InitializeInstance(IRDPENCNamedPipeDirectConnectorCallbacks callbackInstance); 276 | 277 | [PreserveSig] 278 | int TerminateInstance(); 279 | 280 | [PreserveSig] 281 | int StartConnect(string pipeName); 282 | } 283 | 284 | [ComImport, Guid("FB332AE7-000E-4208-92B7-20410CA8382B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 285 | private interface IRDPENCPlatformContext 286 | { 287 | #pragma warning disable IDE1006 // Naming Styles 288 | void _VtblGap0_9(); // skip 9 methods 289 | #pragma warning restore IDE1006 // Naming Styles 290 | int InitializeInstance(); 291 | } 292 | 293 | [ComImport, Guid("D923EFE9-0A6D-4344-92B3-164229DB8D2D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 294 | private interface IRDPENCNamedPipeDirectConnectorCallbacks 295 | { 296 | [PreserveSig] 297 | void OnConnectionCompleted([MarshalAs(UnmanagedType.IUnknown)] object endpoint); 298 | 299 | [PreserveSig] 300 | void OnConnectorError(int hr); 301 | } 302 | #pragma warning restore SYSLIB1096 // Convert to 'GeneratedComInterface' 303 | } 304 | #pragma warning restore IDE0079 // Remove unnecessary suppression 305 | } 306 | --------------------------------------------------------------------------------