├── .gitignore ├── LICENSE ├── README.md └── src ├── AdbCLI.cs ├── Converters ├── BoolToVisibilityConverter.cs └── InverseBoolToVisibilityConverter.cs ├── EmulatorCLI.cs ├── EmulatorControl.xaml ├── EmulatorControl.xaml.cs ├── EmulatorControlViewModel.cs ├── EmulatorMonitor.cs ├── EmulatorProcess.cs ├── EmulatorViewer.Designer.cs ├── EmulatorViewer.cs ├── EmulatorViewer.resx ├── EmulatorWindow.cs ├── Properties └── AssemblyInfo.cs ├── Resources ├── SettingsPanel.png ├── Stop.png └── StopOutline.png ├── ShowToolWindowCommand.cs ├── VSCommandTable.cs ├── VSCommandTable.vsct ├── VsAndroidEm.csproj ├── VsAndroidEm.sln ├── VsAndroidEmPackage.cs ├── Win32API.cs ├── source.extension.cs └── source.extension.vsixmanifest /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 adospace 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vs-android-emulator 2 | This extension embeds the Android emulators running on your system inside a tool window of Visual Studio. 3 | 4 | ## Download from Visual Studio Marketplace 5 | 6 | https://marketplace.visualstudio.com/items?itemName=adospace.vs-android-em 7 | 8 | ## Features 9 | 10 | It automatically detects current emulators and monitors new ones as they are activated. It can handle more than one emulator window, rapidly switching between them. 11 | 12 | Main features: 13 | 14 | - Automatically resizing of the emulator window as you resize the container, 15 | - Support for portrait/landscape mode. 16 | - Show/Hide emulators toolbar 17 | - Ability to close the emulator with or without saving its internal state 18 | 19 | Show the Emulator Preview Window from View->Other Windows->Android Emulator Previewer 20 | 21 | Even if I tested it with different configurations and PCs, it shouldn't be considered yet production ready. 22 | 23 | If you encounter an issue, please report it here: 24 | 25 | https://github.com/adospace/vs-android-emulator/issues 26 | 27 | 28 | 29 | https://github.com/adospace/vs-android-emulator/assets/10573253/56b65e09-927e-4a8a-9d1a-38c559c09a2f 30 | 31 | 32 | 33 | This extension is released under the permissive MIT license and can be used by everyone, even for commercial purposes. 34 | -------------------------------------------------------------------------------- /src/AdbCLI.cs: -------------------------------------------------------------------------------- 1 | using CliWrap; 2 | using CliWrap.Buffered; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace VsAndroidEm; 11 | 12 | class AdbCLI 13 | { 14 | private static async Task ExecuteCommandAsync(params string[] command) 15 | { 16 | var adbDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), 17 | "Android", "android-sdk", "platform-tools"); 18 | var adbPath = Path.Combine(adbDirectory, "adb.exe"); 19 | 20 | return await Cli.Wrap(adbPath) 21 | .WithArguments(command) 22 | .WithValidation(CommandResultValidation.None) 23 | .WithWorkingDirectory(adbDirectory) 24 | .ExecuteAsync(); 25 | } 26 | 27 | private static async Task ExecuteBufferedCommandAsync(params string[] command) 28 | { 29 | var adbDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), 30 | "Android", "android-sdk", "platform-tools"); 31 | var adbPath = Path.Combine(adbDirectory, "adb.exe"); 32 | 33 | var result = await Cli.Wrap(adbPath) 34 | .WithArguments(command) 35 | .WithValidation(CommandResultValidation.None) 36 | .WithWorkingDirectory(adbDirectory) 37 | .ExecuteBufferedAsync(); 38 | 39 | System.Diagnostics.Debug.WriteLine(result.StandardError); 40 | 41 | System.Diagnostics.Debug.WriteLine(result.StandardOutput); 42 | 43 | return result; 44 | } 45 | 46 | public static async Task ShutdownEmulatorAsync(string emulatorName) 47 | => (await ExecuteBufferedCommandAsync("-s", emulatorName, "shell", "reboot", "-p")).ExitCode == 0; 48 | 49 | public static async Task StopEmulatorAsync(string emulatorName) 50 | => (await ExecuteBufferedCommandAsync("-s", emulatorName, "emu", "kill")).ExitCode == 0; 51 | 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/Converters/BoolToVisibilityConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | using System.Windows.Data; 9 | 10 | namespace VsAndroidEm.Converters; 11 | 12 | public class BoolToVisibilityConverter : IValueConverter 13 | { 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return ((bool)value) ? Visibility.Visible : Visibility.Collapsed; 17 | } 18 | 19 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 20 | { 21 | throw new NotImplementedException(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Converters/InverseBoolToVisibilityConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | using System.Windows.Data; 9 | 10 | namespace VsAndroidEm.Converters; 11 | 12 | public class InverseBoolToVisibilityConverter : IValueConverter 13 | { 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return !((bool)value) ? Visibility.Visible : Visibility.Collapsed; 17 | } 18 | 19 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 20 | { 21 | throw new NotImplementedException(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/EmulatorCLI.cs: -------------------------------------------------------------------------------- 1 | using CliWrap.Buffered; 2 | using CliWrap; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using System.IO; 9 | 10 | namespace VsAndroidEm; 11 | 12 | class EmulatorCLI 13 | { 14 | //private static async Task ExecuteCommandAsync(params string[] command) 15 | //{ 16 | // var emulatorDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), 17 | // "Android", "android-sdk", "emulator"); 18 | // var emulatorPath = Path.Combine(emulatorDirectory, "emulator.exe"); 19 | 20 | // return await Cli.Wrap(emulatorPath) 21 | // .WithArguments(command) 22 | // .WithValidation(CommandResultValidation.None) 23 | // .WithWorkingDirectory(emulatorDirectory) 24 | // .ExecuteAsync(); 25 | //} 26 | 27 | private static async Task ExecuteBufferedCommandAsync(params string[] command) 28 | { 29 | ///"C:\Program Files (x86)\Android\android-sdk\emulator" 30 | var emulatorDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), 31 | "Android", "android-sdk", "emulator"); 32 | var emulatorPath = Path.Combine(emulatorDirectory, "emulator.exe"); 33 | 34 | try 35 | { 36 | var result = await Cli.Wrap(emulatorPath) 37 | .WithArguments(command) 38 | .WithValidation(CommandResultValidation.None) 39 | .WithWorkingDirectory(emulatorDirectory) 40 | .ExecuteBufferedAsync(); 41 | 42 | System.Diagnostics.Debug.WriteLine(result.StandardError); 43 | 44 | System.Diagnostics.Debug.WriteLine(result.StandardOutput); 45 | 46 | return result; 47 | 48 | } 49 | catch (Exception ex) 50 | { 51 | System.Diagnostics.Debug.WriteLine(ex); 52 | } 53 | 54 | return new BufferedCommandResult(-1, DateTime.Now, DateTime.Now, string.Empty, string.Empty); 55 | } 56 | 57 | public static void RunEmulator(string avdName) 58 | { 59 | Task.Run(async () => await ExecuteBufferedCommandAsync("-avd", avdName)); 60 | } 61 | 62 | public static async Task GetEmulatorListAsync() 63 | { 64 | var result = await ExecuteBufferedCommandAsync("-list-avds"); 65 | 66 | if (result.ExitCode == 0) 67 | { 68 | return result.StandardOutput.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); 69 | } 70 | 71 | return null; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/EmulatorControl.xaml: -------------------------------------------------------------------------------- 1 |  18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 47 | 48 | 49 | 51 | 52 | 53 | 54 | 55 | 99 | 100 | 131 | 132 | 175 | 176 | 202 | 203 | 219 | 220 | 259 | 260 | 261 | 270 | 271 | 275 | 276 | 283 | 284 | 285 | 286 | 287 | -------------------------------------------------------------------------------- /src/EmulatorControl.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.PlatformUI; 2 | using Microsoft.VisualStudio.Shell; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Collections.ObjectModel; 6 | using System.ComponentModel; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | using System.Windows; 12 | using System.Windows.Controls; 13 | using System.Windows.Data; 14 | using System.Windows.Documents; 15 | using System.Windows.Input; 16 | using System.Windows.Media; 17 | using System.Windows.Media.Imaging; 18 | using System.Windows.Navigation; 19 | using System.Windows.Shapes; 20 | using System.Windows.Threading; 21 | 22 | namespace VsAndroidEm 23 | { 24 | /// 25 | /// Interaction logic for EmulatorControl.xaml 26 | /// 27 | public partial class EmulatorControl : UserControl 28 | { 29 | //public ObservableCollection _processes = new ObservableCollection(); 30 | //private DispatcherTimer _timer; 31 | 32 | public EmulatorControl() 33 | { 34 | InitializeComponent(); 35 | 36 | //_processes.Add(new EmulatorProcess(123, "Emu1", "Emu1")); 37 | //_processes.Add(new EmulatorProcess(123, "Emu2", "Emu2")); 38 | //_processes.Add(new EmulatorProcess(123, "Emu3", "Emu3")); 39 | //toolbar.Visibility = _processes.Count == 0 ? Visibility.Collapsed : Visibility.Visible; 40 | 41 | if (!DesignerProperties.GetIsInDesignMode(this)) 42 | { 43 | DataContext = new EmulatorControlViewModel(); 44 | } 45 | 46 | //tabs.ItemsSource = _processes; 47 | //tabs.SelectionChanged += (s, e) => 48 | //{ 49 | // hostViewPresenter.Content = (tabs.SelectedItem as EmulatorProcess)?.HostView; 50 | // toolbar.Visibility = 51 | // hostViewPresenter.Content == null ? Visibility.Collapsed : Visibility.Visible; 52 | // landingMessage.Visibility = 53 | // hostViewPresenter.Content != null ? Visibility.Collapsed : Visibility.Visible; 54 | //}; 55 | 56 | //ThemedDialogColors 57 | //VsBrushes.ButtonTextKey 58 | //VsResourceKeys. 59 | 60 | this.Loaded += MainWindow_Loaded; 61 | 62 | } 63 | 64 | public EmulatorControlViewModel ViewModel => (EmulatorControlViewModel)DataContext; 65 | 66 | //private void Timer_Tick(object sender, EventArgs e) 67 | //{ 68 | // var avdRunningFolderFiles = Directory.GetFiles(System.IO.Path.Combine( 69 | // Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp", "avd", "running"), "*.ini"); 70 | 71 | // foreach (var file in avdRunningFolderFiles) 72 | // { 73 | // var processId = int.Parse(System.IO.Path.GetFileNameWithoutExtension(file).Substring(4)); //pid_ 74 | 75 | // if (_processes.Any(_ => _.ProcessId == processId)) 76 | // { 77 | // continue; 78 | // } 79 | 80 | 81 | // if (!Win32API.CheckProcessIsRunning(processId)) 82 | // { 83 | // continue; 84 | // } 85 | 86 | // try 87 | // { 88 | // var newEmulatorDetected = EmulatorProcess.CreateFromIniFile(file); 89 | 90 | // newEmulatorDetected.ProcessExited += Emulator_ProcessExited; 91 | // newEmulatorDetected.ErrorRaised += Emulator_ErrorRaised; 92 | 93 | // newEmulatorDetected.Start(); 94 | 95 | // _processes.Add(newEmulatorDetected); 96 | 97 | // tabs.SelectedItem = newEmulatorDetected; 98 | // } 99 | // catch(Exception ex) 100 | // { 101 | // System.Diagnostics.Debug.WriteLine(ex); 102 | // } 103 | 104 | // } 105 | //} 106 | 107 | //private void Emulator_ErrorRaised(object sender, EventArgs e) 108 | //{ 109 | 110 | //} 111 | 112 | //private async void Emulator_ProcessExited(object sender, EventArgs e) 113 | //{ 114 | // try 115 | // { 116 | // var emulatorProcess = (EmulatorProcess)sender; 117 | // await emulatorProcess.StopAsync(); 118 | 119 | // _processes.Remove(emulatorProcess); 120 | // } 121 | // catch (Exception ex) 122 | // { 123 | // System.Diagnostics.Debug.WriteLine(ex); 124 | // } 125 | //} 126 | 127 | private async void MainWindow_Loaded(object sender, RoutedEventArgs e) 128 | { 129 | await ViewModel.RefreshAsync(); 130 | //_timer = new DispatcherTimer 131 | //{ 132 | // Interval = TimeSpan.FromMilliseconds(500) 133 | //}; 134 | //_timer.Tick += Timer_Tick; 135 | //_timer.Start(); 136 | } 137 | 138 | 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/EmulatorControlViewModel.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using EnvDTE; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Collections.ObjectModel; 7 | using System.Diagnostics; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | using System.Windows; 13 | using System.Windows.Input; 14 | using System.Windows.Threading; 15 | using static System.Windows.Forms.VisualStyles.VisualStyleElement; 16 | 17 | namespace VsAndroidEm; 18 | 19 | public class EmulatorControlViewModel : ObservableObject 20 | { 21 | public ObservableCollection _processes = new(); 22 | private readonly DispatcherTimer _timer; 23 | 24 | public EmulatorControlViewModel() 25 | { 26 | _timer = new DispatcherTimer 27 | { 28 | Interval = TimeSpan.FromMilliseconds(500) 29 | }; 30 | 31 | _timer.Tick += Timer_Tick; 32 | _timer.Start(); 33 | 34 | RefreshCommand = new AsyncRelayCommand(RefreshAsync); 35 | } 36 | 37 | public ObservableCollection Processes => _processes; 38 | 39 | static string _selectedEmulatorName; 40 | 41 | private EmulatorProcess _selectedEmulator; 42 | 43 | public EmulatorProcess SelectedEmulator 44 | { 45 | get => _selectedEmulator; 46 | set 47 | { 48 | SetProperty(ref _selectedEmulator, value); 49 | OnPropertyChanged(nameof(StartCommand)); 50 | OnPropertyChanged(nameof(StopCommand)); 51 | OnPropertyChanged(nameof(ShowToolBarWindowCommand)); 52 | OnPropertyChanged(nameof(ShutdownCommand)); 53 | OnPropertyChanged(nameof(ForceAttachmentCommand)); 54 | CommandManager.InvalidateRequerySuggested(); 55 | 56 | _selectedEmulatorName = _selectedEmulator?.Name; 57 | } 58 | } 59 | 60 | public ICommand StartCommand => SelectedEmulator?.StartCommand; 61 | 62 | public ICommand StopCommand => SelectedEmulator?.StopCommand; 63 | 64 | public ICommand ShowToolBarWindowCommand => SelectedEmulator?.ShowToolBarWindowCommand; 65 | 66 | public ICommand ShutdownCommand => SelectedEmulator?.ShutdownCommand; 67 | 68 | public ICommand ForceAttachmentCommand => SelectedEmulator?.ForceAttachmentCommand; 69 | 70 | public ICommand RefreshCommand { get; } 71 | 72 | private void Timer_Tick(object sender, EventArgs e) 73 | { 74 | var avdRunningFolder = Path.Combine( 75 | Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp", "avd", "running"); 76 | 77 | if (!Directory.Exists(avdRunningFolder)) 78 | { 79 | return; 80 | } 81 | 82 | var avdRunningFolderFiles = Directory.GetFiles(avdRunningFolder, "*.ini").ToArray(); 83 | 84 | var emulatorLoaded = false; 85 | 86 | foreach (var processIniFile in avdRunningFolderFiles) 87 | { 88 | var processId = int.Parse(Path.GetFileNameWithoutExtension(processIniFile).Substring(4)); //pid_ 89 | 90 | if (!Win32API.CheckProcessIsRunning(processId)) 91 | { 92 | File.Delete(processIniFile); 93 | continue; 94 | } 95 | 96 | if (_processes.Any(_ => _.ProcessId == processId)) 97 | { 98 | continue; 99 | } 100 | 101 | emulatorLoaded = GetFromIniFile(processIniFile) != null; 102 | } 103 | 104 | if (SelectedEmulator == null && emulatorLoaded) 105 | { 106 | SelectedEmulator = _processes.FirstOrDefault(_ => _.IsStarted); 107 | 108 | //force notifications 109 | OnPropertyChanged(nameof(SelectedEmulator)); 110 | } 111 | } 112 | 113 | private EmulatorProcess GetFromIniFile(string iniFilePath) 114 | { 115 | var processId = int.Parse(Path.GetFileNameWithoutExtension(iniFilePath).Substring(4)); 116 | var iniValues = File.ReadAllLines(iniFilePath) 117 | .Select(_ => _.Split('=')) 118 | .ToDictionary(_ => _[0], _ => _[1]); 119 | 120 | var avdName = iniValues["avd.name"]; 121 | var avdId = iniValues["avd.id"]; 122 | var emulatorName = $"emulator-{iniValues["port.serial"]}"; 123 | 124 | foreach (var process in _processes) 125 | { 126 | if (process.Name == avdName || 127 | process.Name == avdId) 128 | { 129 | process.ProcessExited += Emulator_ProcessExited; 130 | process.ErrorRaised += Emulator_ErrorRaised; 131 | process.ProcessAttached += Emulator_ProcessAttached; 132 | 133 | process.Monitor(processId, emulatorName); 134 | 135 | return process; 136 | } 137 | } 138 | 139 | return null; 140 | } 141 | 142 | private void Emulator_ProcessAttached(object sender, EventArgs e) 143 | { 144 | var currentEmulator = SelectedEmulator; 145 | SelectedEmulator = null; 146 | SelectedEmulator = currentEmulator; 147 | } 148 | 149 | private void Emulator_ErrorRaised(object sender, EventArgs e) 150 | { 151 | 152 | } 153 | 154 | private async void Emulator_ProcessExited(object sender, EventArgs e) 155 | { 156 | try 157 | { 158 | var emulatorProcess = (EmulatorProcess)sender; 159 | emulatorProcess.ProcessExited -= Emulator_ProcessExited; 160 | emulatorProcess.ErrorRaised -= Emulator_ErrorRaised; 161 | emulatorProcess.ProcessAttached -= Emulator_ProcessAttached; 162 | 163 | await emulatorProcess.StopAsync(closeEmulatorProcess: false); 164 | 165 | SelectedEmulator = _processes.FirstOrDefault(_ => _.IsStarted); 166 | 167 | //force notifications 168 | OnPropertyChanged(nameof(SelectedEmulator)); 169 | } 170 | catch (Exception ex) 171 | { 172 | Debug.WriteLine(ex); 173 | } 174 | } 175 | 176 | public async Task RefreshAsync() 177 | { 178 | var avdList = await EmulatorCLI.GetEmulatorListAsync(); 179 | if (avdList == null) 180 | { 181 | return; 182 | } 183 | 184 | _timer.Tick -= Timer_Tick; 185 | _timer.Stop(); 186 | 187 | foreach (var process in _processes.ToArray()) 188 | { 189 | process.ProcessExited -= Emulator_ProcessExited; 190 | process.ErrorRaised -= Emulator_ErrorRaised; 191 | process.ProcessAttached -= Emulator_ProcessAttached; 192 | 193 | await process.StopAsync(closeEmulatorProcess: false, force: false); 194 | } 195 | 196 | _processes.Clear(); 197 | 198 | foreach (var avdName in avdList) 199 | { 200 | if (_processes.Any(_=>_.Name == avdName)) 201 | { 202 | continue; 203 | } 204 | 205 | _processes.Add(new EmulatorProcess(avdName)); 206 | } 207 | 208 | _timer.Tick += Timer_Tick; 209 | _timer.Start(); 210 | 211 | OnPropertyChanged(nameof(Processes)); 212 | } 213 | 214 | public async Task StopAsync() 215 | { 216 | try 217 | { 218 | _timer.Tick -= Timer_Tick; 219 | _timer.Stop(); 220 | 221 | foreach (var process in _processes.ToArray()) 222 | { 223 | await process.StopAsync(force: false); 224 | } 225 | } 226 | catch (Exception ex) 227 | { 228 | Debug.WriteLine(ex); 229 | } 230 | } 231 | 232 | 233 | 234 | } 235 | -------------------------------------------------------------------------------- /src/EmulatorMonitor.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.IO.MemoryMappedFiles; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using System.Windows.Forms; 12 | 13 | namespace VsAndroidEm; 14 | 15 | class EmulatorInfo 16 | { 17 | public string AvdName { get; set; } 18 | 19 | public int EmulatorProcessId { get; set; } 20 | 21 | public int VisualStudioProcessId { get; set; } 22 | 23 | public long MainWindowHandle { get; set; } 24 | 25 | public long ChildWindowHandle { get; set; } 26 | 27 | public long ToolWindowHandle { get; set; } 28 | 29 | } 30 | 31 | class EmulatorMonitor 32 | { 33 | private static readonly Mutex _sharedLock = new(false, nameof(VsAndroidEm)); 34 | 35 | public EmulatorInfo GetExistingEmulatorInfo(string avdName) 36 | { 37 | try 38 | { 39 | if (!_sharedLock.WaitOne(1000)) 40 | { 41 | return null; 42 | } 43 | 44 | var sharedFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "_emulatorMonitor.info"); 45 | 46 | if (!File.Exists(sharedFilePath)) 47 | { 48 | return null; 49 | } 50 | 51 | var infos = JsonConvert.DeserializeObject>(File.ReadAllText(sharedFilePath)); 52 | 53 | if (infos == null) 54 | { 55 | return null; 56 | } 57 | 58 | bool infoMustBeSavedBack = false; 59 | foreach (var info in infos.ToArray()) 60 | { 61 | if (string.IsNullOrEmpty(info.AvdName)) 62 | { 63 | infoMustBeSavedBack = true; 64 | infos.Remove(info); 65 | continue; 66 | } 67 | 68 | if (info.EmulatorProcessId != 0) 69 | { 70 | if (!Win32API.CheckProcessIsRunning(info.EmulatorProcessId)) 71 | { 72 | infos.Remove(info); 73 | infoMustBeSavedBack = true; 74 | }; 75 | } 76 | 77 | if (info.VisualStudioProcessId != 0) 78 | { 79 | if (!Win32API.CheckProcessIsRunning(info.VisualStudioProcessId)) 80 | { 81 | infos.Remove(info); 82 | infoMustBeSavedBack = true; 83 | }; 84 | } 85 | } 86 | 87 | var foundEmulatorInfoWithProcessId = infos.FirstOrDefault(_ => _.AvdName == avdName && _.EmulatorProcessId != 0); 88 | var foundEmulatorInfo = infos.FirstOrDefault(_ => _.AvdName == avdName && _.EmulatorProcessId == 0); 89 | 90 | if (foundEmulatorInfo != null && foundEmulatorInfoWithProcessId != null) 91 | { 92 | infos.Remove(foundEmulatorInfo); 93 | infoMustBeSavedBack = true; 94 | } 95 | 96 | if (infoMustBeSavedBack) 97 | { 98 | var json = JsonConvert.SerializeObject(infos); 99 | 100 | File.WriteAllText(sharedFilePath, json); 101 | } 102 | 103 | return foundEmulatorInfoWithProcessId ?? foundEmulatorInfo; 104 | 105 | } 106 | finally 107 | { 108 | _sharedLock.ReleaseMutex(); 109 | } 110 | } 111 | 112 | public void SaveEmulatorInfo(EmulatorInfo info) 113 | { 114 | try 115 | { 116 | if (!_sharedLock.WaitOne(1000)) 117 | { 118 | return; 119 | } 120 | 121 | var sharedFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "_emulatorMonitor.info"); 122 | 123 | var infos = new List(); 124 | 125 | if (File.Exists(sharedFilePath)) 126 | { 127 | infos = JsonConvert.DeserializeObject(File.ReadAllText(sharedFilePath))?.ToList() ?? new List(); 128 | } 129 | 130 | infos.RemoveAll(_ => _.AvdName == info.AvdName || string.IsNullOrEmpty(_.AvdName)); 131 | infos.Add(info); 132 | 133 | var json = JsonConvert.SerializeObject(infos); 134 | 135 | File.WriteAllText(sharedFilePath, json); 136 | } 137 | finally 138 | { 139 | _sharedLock.ReleaseMutex(); 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/EmulatorProcess.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using EnvDTE; 4 | using Microsoft.VisualStudio.PlatformUI; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.ComponentModel; 8 | using System.Diagnostics; 9 | using System.IO; 10 | using System.Linq; 11 | using System.Text; 12 | using System.Threading.Tasks; 13 | using System.Windows; 14 | using System.Windows.Forms.Integration; 15 | using System.Windows.Input; 16 | using System.Windows.Threading; 17 | 18 | namespace VsAndroidEm 19 | { 20 | public class EmulatorProcess : CommunityToolkit.Mvvm.ComponentModel.ObservableObject 21 | { 22 | private readonly EmulatorViewer _viewer = new(); 23 | private bool _isBusy; 24 | 25 | public EmulatorProcess(string name) 26 | { 27 | Name = name; 28 | StartCommand = new RelayCommand(Start, () => !IsRunning && !CanBeAttached); 29 | StopCommand = new AsyncRelayCommand(()=>StopAsync(force: true), () => IsRunning); 30 | ShowToolBarWindowCommand = new RelayCommand(ShowToolWindow, () => IsRunning && !CanBeAttached); 31 | ShutdownCommand = new AsyncRelayCommand(ShutdownAsync, () => IsRunning); 32 | ForceAttachmentCommand = new RelayCommand(ForceAttachment, () => true); 33 | 34 | HostView = new WindowsFormsHost 35 | { 36 | Child = _viewer, 37 | }; 38 | 39 | _viewer.ProcessAttached += (s, e) => 40 | { 41 | Dispatcher.CurrentDispatcher.BeginInvoke(() => 42 | { 43 | OnPropertyChanged(nameof(IsStarted)); 44 | OnPropertyChanged(nameof(IsRunning)); 45 | OnPropertyChanged(nameof(FormatName)); 46 | //OnPropertyChanged(nameof(IsReadyToAcceptCommand)); 47 | 48 | CommandManager.InvalidateRequerySuggested(); 49 | 50 | ProcessAttached?.Invoke(this, e); 51 | }); 52 | }; 53 | 54 | _viewer.ProcessExited += (s, e) => 55 | { 56 | Dispatcher.CurrentDispatcher.BeginInvoke(() => 57 | { 58 | OnPropertyChanged(nameof(IsStarted)); 59 | OnPropertyChanged(nameof(IsRunning)); 60 | OnPropertyChanged(nameof(FormatName)); 61 | //OnPropertyChanged(nameof(IsReadyToAcceptCommand)); 62 | 63 | CommandManager.InvalidateRequerySuggested(); 64 | 65 | ProcessExited?.Invoke(this, e); 66 | }); 67 | }; 68 | 69 | _viewer.ErrorRaised += (s, e) => 70 | { 71 | Dispatcher.CurrentDispatcher.BeginInvoke(() => 72 | { 73 | OnPropertyChanged(nameof(IsStarted)); 74 | OnPropertyChanged(nameof(FormatName)); 75 | OnPropertyChanged(nameof(IsRunning)); 76 | //OnPropertyChanged(nameof(IsReadyToAcceptCommand)); 77 | OnPropertyChanged(nameof(LastErrorMessage)); 78 | OnPropertyChanged(nameof(LastErrorMessageVisibility)); 79 | 80 | CommandManager.InvalidateRequerySuggested(); 81 | 82 | ErrorRaised?.Invoke(this, e); 83 | }); 84 | }; 85 | 86 | _viewer.CanBeAttachedChanged += (s, e) => 87 | { 88 | Dispatcher.CurrentDispatcher.BeginInvoke(() => 89 | { 90 | OnPropertyChanged(nameof(CanBeAttached)); 91 | OnPropertyChanged(nameof(IsRunning)); 92 | OnPropertyChanged(nameof(FormatName)); 93 | 94 | CommandManager.InvalidateRequerySuggested(); 95 | }); 96 | }; 97 | } 98 | public ICommand StartCommand { get; } 99 | 100 | public ICommand ShowToolBarWindowCommand { get; } 101 | 102 | public ICommand StopCommand { get; } 103 | 104 | public ICommand ShutdownCommand { get; } 105 | 106 | public ICommand ForceAttachmentCommand { get; } 107 | 108 | public int ProcessId { get; private set; } 109 | 110 | public string Name { get; } 111 | 112 | public string FormatName => $"{Name}{(IsStarted ? "(Running)" : string.Empty)}"; 113 | 114 | public WindowsFormsHost HostView { get; } 115 | 116 | public bool IsStarted => _viewer.IsStarted; 117 | 118 | //public bool IsReadyToAcceptCommand => _viewer.IsReadyToAcceptCommand; 119 | 120 | public bool IsRunning => !IsBusy && IsStarted/* && IsReadyToAcceptCommand*/; 121 | 122 | public string LastErrorMessage => _viewer.LastErrorMessage; 123 | 124 | public bool CanBeAttached => _viewer.CanBeAttached; 125 | 126 | public bool IsBusy 127 | { 128 | get => _isBusy; 129 | set 130 | { 131 | SetProperty(ref _isBusy, value); 132 | CommandManager.InvalidateRequerySuggested(); 133 | } 134 | } 135 | 136 | public Visibility LastErrorMessageVisibility 137 | => !string.IsNullOrEmpty(_viewer.LastErrorMessage) ? Visibility.Visible : Visibility.Collapsed; 138 | 139 | public event EventHandler ProcessExited; 140 | 141 | public event EventHandler ProcessAttached; 142 | 143 | public event EventHandler ErrorRaised; 144 | 145 | public void ShowToolWindow() 146 | { 147 | _viewer.ShowToolWindow = !_viewer.ShowToolWindow; 148 | } 149 | 150 | public void Monitor(int processId, string emulatorName) 151 | { 152 | IsBusy = true; 153 | ProcessId = processId; 154 | 155 | _viewer.Monitor(Name, processId, emulatorName); 156 | 157 | IsBusy = false; 158 | } 159 | 160 | public void Start() 161 | { 162 | _viewer.Start(Name); 163 | } 164 | 165 | 166 | public async Task StopAsync(bool closeEmulatorProcess = true, bool shutdownEmulator = false, bool force = true) 167 | { 168 | IsBusy = true; 169 | 170 | await _viewer.StopAsync(closeEmulatorProcess, shutdownEmulator, force); 171 | 172 | ProcessId = 0; 173 | 174 | IsBusy = false; 175 | } 176 | 177 | public async Task ShutdownAsync() 178 | { 179 | IsBusy = true; 180 | 181 | await _viewer.StopAsync(shutdownEmulator: true, force: true); 182 | 183 | IsBusy = false; 184 | } 185 | 186 | private void ForceAttachment() 187 | { 188 | _viewer.ForceAttachment = true; 189 | } 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/EmulatorViewer.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace VsAndroidEm 2 | { 3 | partial class EmulatorViewer 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Component Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.childContainer = new System.Windows.Forms.Panel(); 32 | this.toolContainer = new System.Windows.Forms.Panel(); 33 | this.emulatorContainer = new System.Windows.Forms.Panel(); 34 | this.childInternalContainer = new System.Windows.Forms.Panel(); 35 | this.childContainer.SuspendLayout(); 36 | this.emulatorContainer.SuspendLayout(); 37 | this.SuspendLayout(); 38 | // 39 | // childContainer 40 | // 41 | this.childContainer.BackColor = System.Drawing.Color.Transparent; 42 | this.childContainer.Controls.Add(this.childInternalContainer); 43 | this.childContainer.Location = new System.Drawing.Point(46, 38); 44 | this.childContainer.Name = "childContainer"; 45 | this.childContainer.Size = new System.Drawing.Size(453, 425); 46 | this.childContainer.TabIndex = 0; 47 | // 48 | // toolContainer 49 | // 50 | this.toolContainer.BackColor = System.Drawing.Color.Transparent; 51 | this.toolContainer.Dock = System.Windows.Forms.DockStyle.Right; 52 | this.toolContainer.Location = new System.Drawing.Point(740, 0); 53 | this.toolContainer.Name = "toolContainer"; 54 | this.toolContainer.Size = new System.Drawing.Size(0, 675); 55 | this.toolContainer.TabIndex = 1; 56 | // 57 | // emulatorContainer 58 | // 59 | this.emulatorContainer.BackColor = System.Drawing.Color.Transparent; 60 | this.emulatorContainer.Controls.Add(this.childContainer); 61 | this.emulatorContainer.Dock = System.Windows.Forms.DockStyle.Fill; 62 | this.emulatorContainer.Location = new System.Drawing.Point(0, 0); 63 | this.emulatorContainer.Name = "emulatorContainer"; 64 | this.emulatorContainer.Size = new System.Drawing.Size(740, 675); 65 | this.emulatorContainer.TabIndex = 2; 66 | // 67 | // childInternalContainer 68 | // 69 | this.childInternalContainer.BackColor = System.Drawing.Color.Transparent; 70 | this.childInternalContainer.Location = new System.Drawing.Point(86, 57); 71 | this.childInternalContainer.Name = "childInternalContainer"; 72 | this.childInternalContainer.Size = new System.Drawing.Size(200, 100); 73 | this.childInternalContainer.TabIndex = 0; 74 | // 75 | // EmulatorViewer 76 | // 77 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 78 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 79 | this.Controls.Add(this.emulatorContainer); 80 | this.Controls.Add(this.toolContainer); 81 | this.Name = "EmulatorViewer"; 82 | this.Size = new System.Drawing.Size(740, 675); 83 | this.childContainer.ResumeLayout(false); 84 | this.emulatorContainer.ResumeLayout(false); 85 | this.ResumeLayout(false); 86 | 87 | } 88 | 89 | #endregion 90 | 91 | private System.Windows.Forms.Panel childContainer; 92 | private System.Windows.Forms.Panel toolContainer; 93 | private System.Windows.Forms.Panel emulatorContainer; 94 | private System.Windows.Forms.Panel childInternalContainer; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/EmulatorViewer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Build.Framework.XamlTypes; 2 | using Microsoft.VisualStudio.RpcContracts; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel; 6 | using System.Data; 7 | using System.Diagnostics; 8 | using System.Drawing; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using System.Windows.Forms; 14 | 15 | 16 | namespace VsAndroidEm 17 | { 18 | public partial class EmulatorViewer : UserControl 19 | { 20 | private string _avdName; 21 | private string _emulatorName; 22 | private Process _process; 23 | private IntPtr _mainWindowHandle; 24 | private IntPtr _childWindowHandle; 25 | private IntPtr _toolWindowHandle; 26 | private bool _toolWindowVisible; 27 | 28 | private bool _hosted; 29 | private bool _updateChildWindowSize = true; 30 | private Size _lastChildWindowSize; 31 | private Size _toolWindowSize; 32 | private Size _emulatorFrameSize; 33 | 34 | private bool _inError; 35 | 36 | private static readonly SemaphoreSlim _lockSemaphore = new(1, 1); 37 | 38 | private static readonly EmulatorMonitor _emulatorMonitor = new(); 39 | 40 | System.Windows.Forms.Timer _timerUpdate; 41 | 42 | public EmulatorViewer() 43 | { 44 | InitializeComponent(); 45 | } 46 | 47 | public void Start(string avdName) 48 | { 49 | _avdName = avdName; 50 | 51 | var visualStudioProcessId = Process.GetCurrentProcess().Id; 52 | _emulatorMonitor.SaveEmulatorInfo(new EmulatorInfo 53 | { 54 | AvdName = avdName, 55 | VisualStudioProcessId = visualStudioProcessId 56 | }); 57 | 58 | EmulatorCLI.RunEmulator(avdName); 59 | } 60 | 61 | public void Monitor(string avdName, int processId, string emulatorName) 62 | { 63 | lock (this) 64 | { 65 | if (IsStarted) 66 | { 67 | return; 68 | } 69 | 70 | try 71 | { 72 | _process = Process.GetProcessById(processId); 73 | } 74 | catch (ArgumentException) 75 | { 76 | return; 77 | } 78 | 79 | if (_process.HasExited) 80 | { 81 | _process = null; 82 | return; 83 | } 84 | 85 | _emulatorName = emulatorName; 86 | _avdName = avdName; 87 | 88 | _timerUpdate = new System.Windows.Forms.Timer 89 | { 90 | Interval = 500 91 | }; 92 | _timerUpdate.Tick += TimerUpdate_Tick; 93 | _timerUpdate.Start(); 94 | } 95 | } 96 | 97 | public async Task StopAsync(bool closeEmulatorProcess = true, bool shutdownEmulator = false, bool force = false) 98 | { 99 | try 100 | { 101 | await _lockSemaphore.WaitAsync(); 102 | 103 | if (!IsStarted) 104 | { 105 | return; 106 | } 107 | 108 | await StopCoreAsync(closeEmulatorProcess, shutdownEmulator, force); 109 | 110 | if (_timerUpdate != null) 111 | { 112 | _timerUpdate.Stop(); 113 | _timerUpdate.Tick -= TimerUpdate_Tick; 114 | _timerUpdate.Dispose(); 115 | _timerUpdate = null; 116 | } 117 | } 118 | finally 119 | { 120 | _lockSemaphore.Release(); 121 | } 122 | } 123 | 124 | private async Task WaitForProcessExitAsync(int milliseconds) 125 | { 126 | Task waitForExitTask = Task.Run(() => _process.WaitForExit()); 127 | 128 | Task delayTask = Task.Delay(milliseconds); 129 | 130 | Task completedTask = await Task.WhenAny(waitForExitTask, delayTask); 131 | 132 | return (completedTask == waitForExitTask); 133 | } 134 | 135 | private async Task StopCoreAsync(bool closeEmulatorProcess, bool shutdownEmulator = false, bool force = false) 136 | { 137 | if (closeEmulatorProcess && !force) 138 | { 139 | var emulatorInfo = _emulatorMonitor.GetExistingEmulatorInfo(_avdName); 140 | 141 | if (emulatorInfo != null) 142 | { 143 | var visualStudioProcessId = Process.GetCurrentProcess().Id; 144 | if (emulatorInfo.VisualStudioProcessId != visualStudioProcessId) 145 | { 146 | closeEmulatorProcess = false; 147 | } 148 | } 149 | } 150 | 151 | if (_process != null && closeEmulatorProcess) 152 | { 153 | // Command to gracefully close the emulator 154 | if (!_process.HasExited && 155 | (shutdownEmulator ? await AdbCLI.ShutdownEmulatorAsync(_emulatorName) : await AdbCLI.StopEmulatorAsync(_emulatorName))) 156 | { 157 | if (await WaitForProcessExitAsync(5000)) 158 | { 159 | _process = null; 160 | ProcessExited?.Invoke(this, EventArgs.Empty); 161 | } 162 | } 163 | } 164 | 165 | if (_process != null && closeEmulatorProcess) 166 | { 167 | try 168 | { 169 | if (!_process.HasExited) 170 | { 171 | _process.Kill(); 172 | _process = null; 173 | ProcessExited?.Invoke(this, EventArgs.Empty); 174 | } 175 | } 176 | catch (Exception) 177 | { 178 | 179 | } 180 | } 181 | 182 | _process = null; 183 | _mainWindowHandle = IntPtr.Zero; 184 | _childWindowHandle = IntPtr.Zero; 185 | _hosted = false; 186 | _inError = false; 187 | _updateChildWindowSize = true; 188 | _toolWindowHandle = IntPtr.Zero; 189 | _toolWindowVisible = false; 190 | _emulatorFrameSize = default; 191 | _lastChildWindowSize = default; 192 | 193 | ShowToolWindow = false; 194 | LastErrorMessage = null; 195 | } 196 | 197 | public bool IsStarted => _process != null && !_process.HasExited; 198 | 199 | public string LastErrorMessage { get; private set; } 200 | 201 | public bool ShowToolWindow { get; set; } 202 | 203 | public bool IsReadyToAcceptCommand => _process == null || _hosted; 204 | 205 | public bool CanBeAttached { get; set; } 206 | 207 | public bool ForceAttachment { get; set; } 208 | 209 | public event EventHandler ProcessExited; 210 | 211 | public event EventHandler ProcessAttached; 212 | 213 | public event EventHandler ErrorRaised; 214 | 215 | public event EventHandler CanBeAttachedChanged; 216 | 217 | private void TimerUpdate_Tick(object sender, EventArgs e) 218 | { 219 | lock (this) 220 | { 221 | UpdateInternals(); 222 | } 223 | } 224 | 225 | private void UpdateInternals() 226 | { 227 | if (_inError) 228 | { 229 | return; 230 | } 231 | 232 | if (!IsStarted) 233 | { 234 | return; 235 | } 236 | 237 | if (_process.HasExited) 238 | { 239 | ProcessExited?.Invoke(this, EventArgs.Empty); 240 | 241 | return; 242 | } 243 | 244 | var emulatorInfo = _emulatorMonitor.GetExistingEmulatorInfo(_avdName); 245 | 246 | if (emulatorInfo != null && emulatorInfo.MainWindowHandle != 0) 247 | { 248 | var visualStudioProcessId = Process.GetCurrentProcess().Id; 249 | if (emulatorInfo.VisualStudioProcessId == visualStudioProcessId) 250 | { 251 | CanBeAttached = false; 252 | ForceAttachment = false; 253 | 254 | if (_mainWindowHandle == IntPtr.Zero) 255 | { 256 | _mainWindowHandle = new IntPtr(emulatorInfo.MainWindowHandle); 257 | } 258 | if (_toolWindowHandle == IntPtr.Zero) 259 | { 260 | _toolWindowHandle = new IntPtr(emulatorInfo.ToolWindowHandle); 261 | } 262 | } 263 | else 264 | { 265 | if (CanBeAttached && ForceAttachment) 266 | { 267 | _mainWindowHandle = new IntPtr(emulatorInfo.MainWindowHandle); 268 | _childWindowHandle = new IntPtr(emulatorInfo.ChildWindowHandle); 269 | _toolWindowHandle = new IntPtr(emulatorInfo.ToolWindowHandle); 270 | CanBeAttached = false; 271 | ForceAttachment = true; 272 | CanBeAttachedChanged?.Invoke(this, EventArgs.Empty); 273 | } 274 | else if (!CanBeAttached) 275 | { 276 | _mainWindowHandle = IntPtr.Zero; 277 | _childWindowHandle = IntPtr.Zero; 278 | _hosted = false; 279 | _inError = false; 280 | _updateChildWindowSize = true; 281 | _toolWindowHandle = IntPtr.Zero; 282 | _toolWindowVisible = false; 283 | _emulatorFrameSize = default; 284 | _lastChildWindowSize = default; 285 | 286 | ShowToolWindow = false; 287 | LastErrorMessage = null; 288 | 289 | CanBeAttached = true; 290 | ForceAttachment = false; 291 | CanBeAttachedChanged?.Invoke(this, EventArgs.Empty); 292 | 293 | return; 294 | } 295 | else 296 | { 297 | return; 298 | } 299 | } 300 | } 301 | 302 | if (_mainWindowHandle == IntPtr.Zero) 303 | { 304 | if (!Win32API.IsWindowVisible(_process.MainWindowHandle) || 305 | !Win32API.GetWindowRect(_process.MainWindowHandle, out var _)) 306 | { 307 | //main window not ready 308 | return; 309 | } 310 | 311 | _mainWindowHandle = _process.MainWindowHandle; 312 | if (_mainWindowHandle == IntPtr.Zero) 313 | { 314 | return; 315 | } 316 | } 317 | 318 | if (_childWindowHandle == IntPtr.Zero) 319 | { 320 | _childWindowHandle = Win32API.GetAllChildWindows(_mainWindowHandle)?.FirstOrDefault() ?? IntPtr.Zero; 321 | 322 | if (!Win32API.GetWindowRect(_childWindowHandle, out var childWindowRect)) 323 | { 324 | _childWindowHandle = IntPtr.Zero; 325 | } 326 | 327 | if (_childWindowHandle == IntPtr.Zero) 328 | { 329 | return; 330 | } 331 | } 332 | 333 | if (!_hosted) 334 | { 335 | try 336 | { 337 | if (_toolWindowHandle == IntPtr.Zero) 338 | { 339 | var allProcessWindows = Win32API.EnumerateProcessWindowHandles(_process.Id) 340 | .Where(_ => _ != _mainWindowHandle) 341 | .ToList(); 342 | 343 | foreach (var processWindowHandle in allProcessWindows) 344 | { 345 | StringBuilder className = new(256); 346 | 347 | if (0 == Win32API.GetClassName(processWindowHandle, className, className.Capacity)) 348 | { 349 | throw new InvalidOperationException($"Unable to get window class name ({GetLastErrorMessage()})"); 350 | } 351 | 352 | if (className.ToString() == "Qt5QWindowToolSaveBits" || 353 | className.ToString() == "Qt653QWindowToolSaveBits") 354 | { 355 | _toolWindowHandle = processWindowHandle; 356 | break; 357 | } 358 | } 359 | 360 | allProcessWindows 361 | .Where(_ => _ != _toolWindowHandle) 362 | .ToList() 363 | .ForEach(handle => Win32API.ShowWindow(handle, Win32API.SW_HIDE)); 364 | } 365 | 366 | if (!Win32API.GetWindowRect(_childWindowHandle, out var childWindowRect)) 367 | { 368 | _childWindowHandle = IntPtr.Zero; 369 | return; 370 | } 371 | 372 | _lastChildWindowSize = new Size(childWindowRect.Right - childWindowRect.Left, childWindowRect.Bottom - childWindowRect.Top); 373 | 374 | childContainer.Width = _lastChildWindowSize.Width; 375 | childContainer.Height = _lastChildWindowSize.Height; 376 | childContainer.Left = Math.Max(0, (emulatorContainer.Width - childContainer.Width) / 2); 377 | childContainer.Top = Math.Max(0, (emulatorContainer.Height - childContainer.Height) / 2); 378 | 379 | var childStyle = (IntPtr)(Win32API.WindowStyles.WS_CHILD | 380 | // the parent cannot draw over the child's area. this is needed to avoid refresh issues 381 | Win32API.WindowStyles.WS_CLIPCHILDREN | 382 | Win32API.WindowStyles.WS_VISIBLE | 383 | Win32API.WindowStyles.WS_MAXIMIZE 384 | ); 385 | 386 | if (0 == Win32API.SetWindowLong(_mainWindowHandle, Win32API.GWL_STYLE, (int)childStyle)) 387 | { 388 | throw new InvalidOperationException($"Unable to set main window style ({GetLastErrorMessage()})"); 389 | } 390 | 391 | if (IntPtr.Zero == Win32API.SetParent(_mainWindowHandle, childInternalContainer.Handle)) 392 | { 393 | throw new InvalidOperationException($"Unable to relocate emulator main window ({GetLastErrorMessage()})"); 394 | } 395 | 396 | //setup tool window 397 | if (!Win32API.GetWindowRect(_toolWindowHandle, out var toolWindowRect)) 398 | { 399 | throw new InvalidOperationException($"Unable to get tool window rect ({GetLastErrorMessage()})"); 400 | } 401 | 402 | _toolWindowSize = new Size(toolWindowRect.Right - toolWindowRect.Left, toolWindowRect.Bottom - toolWindowRect.Top); 403 | 404 | childStyle = (IntPtr)(Win32API.WindowStyles.WS_CHILD | 405 | // the parent cannot draw over the child's area. this is needed to avoid refresh issues 406 | Win32API.WindowStyles.WS_CLIPCHILDREN | 407 | Win32API.WindowStyles.WS_VISIBLE | 408 | Win32API.WindowStyles.WS_MAXIMIZE 409 | ); 410 | 411 | if (0 == Win32API.SetWindowLong(_toolWindowHandle, Win32API.GWL_STYLE, (int)childStyle)) 412 | { 413 | throw new InvalidOperationException($"Unable to set tool window style ({GetLastErrorMessage()})"); 414 | } 415 | 416 | if (IntPtr.Zero == Win32API.SetParent(_toolWindowHandle, toolContainer.Handle)) 417 | { 418 | throw new InvalidOperationException($"Unable to relocate emulator tool window ({GetLastErrorMessage()})"); 419 | } 420 | 421 | var visualStudioProcessId = Process.GetCurrentProcess().Id; 422 | 423 | _emulatorMonitor.SaveEmulatorInfo(new EmulatorInfo 424 | { 425 | EmulatorProcessId = _process.Id, 426 | AvdName = _avdName, 427 | VisualStudioProcessId = visualStudioProcessId, 428 | MainWindowHandle = _mainWindowHandle.ToInt64(), 429 | ChildWindowHandle = _childWindowHandle.ToInt64(), 430 | ToolWindowHandle = _toolWindowHandle.ToInt64(), 431 | }); 432 | } 433 | catch (Exception ex) 434 | { 435 | Debug.WriteLine($"[{_emulatorName}] Exception: {ex}"); 436 | 437 | _inError = true; 438 | LastErrorMessage = ex.Message; 439 | ErrorRaised?.Invoke(this, EventArgs.Empty); 440 | 441 | return; 442 | } 443 | 444 | Debug.WriteLine($"[{_emulatorName}] MainWindow attached"); 445 | 446 | ProcessAttached?.Invoke(this, EventArgs.Empty); 447 | 448 | _hosted = true; 449 | } 450 | 451 | if (_toolWindowVisible) 452 | { 453 | try 454 | { 455 | if (!Win32API.GetWindowRect(_toolWindowHandle, out var toolWindowRect)) 456 | { 457 | throw new InvalidOperationException("Unable to get tool window rect"); 458 | } 459 | 460 | if (toolWindowRect.Left != 0 || toolWindowRect.Right != 0) 461 | { 462 | Debug.WriteLine("Win32API.SetWindowPos(_toolWindowHandle)"); 463 | 464 | Win32API.SetWindowPos(_toolWindowHandle, IntPtr.Zero, 0, 0, _toolWindowSize.Width, _toolWindowSize.Height, Win32API.SetWindowPosFlags.ShowWindow); 465 | 466 | Win32API.UpdateWindow(_toolWindowHandle); 467 | } 468 | } 469 | catch (Exception ex) 470 | { 471 | Debug.WriteLine($"[{_emulatorName}] Exception: {ex}"); 472 | 473 | _inError = true; 474 | LastErrorMessage = ex.Message; 475 | ErrorRaised?.Invoke(this, EventArgs.Empty); 476 | return; 477 | } 478 | } 479 | 480 | if (ShowToolWindow && !_toolWindowVisible) 481 | { 482 | toolContainer.Width = _toolWindowSize.Width; 483 | _toolWindowVisible = true; 484 | _updateChildWindowSize = true; 485 | } 486 | else if (!ShowToolWindow && _toolWindowVisible) 487 | { 488 | toolContainer.Width = 0; 489 | _toolWindowVisible = false; 490 | _updateChildWindowSize = true; 491 | } 492 | 493 | if (_updateChildWindowSize) 494 | { 495 | try 496 | { 497 | if (!Win32API.SetWindowPos(_mainWindowHandle, IntPtr.Zero, 0, 0, emulatorContainer.Width + _emulatorFrameSize.Width, emulatorContainer.Height + _emulatorFrameSize.Height, Win32API.SetWindowPosFlags.ShowWindow)) 498 | { 499 | throw new InvalidOperationException($"Unable to set main window position ({GetLastErrorMessage()})"); 500 | } 501 | 502 | if (!Win32API.UpdateWindow(_mainWindowHandle)) 503 | { 504 | throw new InvalidOperationException($"Unable to update main window ({GetLastErrorMessage()})"); 505 | } 506 | 507 | } 508 | catch (Exception ex) 509 | { 510 | Debug.WriteLine($"[{_emulatorName}] Exception: {ex}"); 511 | 512 | _inError = true; 513 | LastErrorMessage = ex.Message; 514 | ErrorRaised?.Invoke(this, EventArgs.Empty); 515 | return; 516 | } 517 | } 518 | 519 | try 520 | { 521 | if (Win32API.GetWindowRect(_childWindowHandle, out var childWindowRect) && 522 | Win32API.GetWindowRect(_mainWindowHandle, out var mainWindowWindowRect)) 523 | { 524 | var currentChildWindowSize = new Size(childWindowRect.Right - childWindowRect.Left, childWindowRect.Bottom - childWindowRect.Top); 525 | 526 | if (currentChildWindowSize != _lastChildWindowSize || _updateChildWindowSize) 527 | { 528 | _lastChildWindowSize = new Size(childWindowRect.Right - childWindowRect.Left, childWindowRect.Bottom - childWindowRect.Top); 529 | 530 | childContainer.Width = _lastChildWindowSize.Width; 531 | childContainer.Height = _lastChildWindowSize.Height; 532 | childContainer.Left = Math.Max(0, (emulatorContainer.Width - childContainer.Width) / 2); 533 | childContainer.Top = Math.Max(0, (emulatorContainer.Height - childContainer.Height) / 2); 534 | 535 | _emulatorFrameSize = new Size(childWindowRect.Left - mainWindowWindowRect.Left, childWindowRect.Top - mainWindowWindowRect.Top); 536 | 537 | childInternalContainer.Left = -_emulatorFrameSize.Width; 538 | childInternalContainer.Top = -_emulatorFrameSize.Height; 539 | childInternalContainer.Width = -childInternalContainer.Left + childContainer.Width; 540 | childInternalContainer.Height = -childInternalContainer.Top + childContainer.Height; 541 | 542 | Debug.WriteLine($"[{_emulatorName}] MainWindow position adjusted"); 543 | 544 | Win32API.ShowWindow(_mainWindowHandle, Win32API.SW_SHOW); 545 | Win32API.ShowWindow(_toolWindowHandle, Win32API.SW_SHOW); 546 | 547 | _updateChildWindowSize = false; 548 | 549 | ProcessAttached?.Invoke(this, EventArgs.Empty); 550 | } 551 | 552 | _timerUpdate.Interval = 100; 553 | } 554 | else 555 | { 556 | _childWindowHandle = IntPtr.Zero; 557 | _updateChildWindowSize = true; 558 | } 559 | } 560 | catch (Exception ex) 561 | { 562 | Debug.WriteLine($"[{_emulatorName}] Exception: {ex}"); 563 | 564 | _inError = true; 565 | LastErrorMessage = ex.Message; 566 | ErrorRaised?.Invoke(this, EventArgs.Empty); 567 | return; 568 | } 569 | } 570 | 571 | private string GetLastErrorMessage() 572 | { 573 | uint errorCode = Win32API.GetLastError(); 574 | 575 | if (errorCode == 0) 576 | { 577 | return string.Empty; 578 | } 579 | 580 | StringBuilder messageBuffer = new(512); 581 | Win32API.FormatMessage(Win32API.FORMAT_MESSAGE_FROM_SYSTEM | Win32API.FORMAT_MESSAGE_IGNORE_INSERTS, 582 | IntPtr.Zero, errorCode, 0, messageBuffer, (uint)messageBuffer.Capacity, IntPtr.Zero); 583 | 584 | return $"Error Code: {errorCode} - {messageBuffer.ToString().TrimEnd('\r', '\n')}"; 585 | } 586 | 587 | protected override void OnResize(EventArgs e) 588 | { 589 | _updateChildWindowSize = true; 590 | base.OnResize(e); 591 | } 592 | } 593 | 594 | } 595 | -------------------------------------------------------------------------------- /src/EmulatorViewer.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 | -------------------------------------------------------------------------------- /src/EmulatorWindow.cs: -------------------------------------------------------------------------------- 1 | using Community.VisualStudio.Toolkit; 2 | using Microsoft.VisualStudio.Imaging; 3 | using Microsoft.VisualStudio.Shell; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Runtime.InteropServices; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using System.Windows; 12 | 13 | namespace VsAndroidEm 14 | { 15 | public class EmulatorWindow : BaseToolWindow 16 | { 17 | private Pane _pane; 18 | private EmulatorControl _emulatorControl; 19 | 20 | public override string GetTitle(int toolWindowId) => "Android Emulator Previewer"; 21 | 22 | public override Type PaneType => typeof(Pane); 23 | 24 | public override Task CreateAsync(int toolWindowId, CancellationToken cancellationToken) 25 | { 26 | return Task.FromResult(_emulatorControl = new EmulatorControl()); 27 | } 28 | 29 | public override void SetPane(ToolWindowPane pane, int toolWindowId) 30 | { 31 | _pane = (Pane)pane; 32 | _pane.Closing += Pane_Closing; 33 | base.SetPane(pane, toolWindowId); 34 | } 35 | 36 | private async void Pane_Closing(object sender, EventArgs e) 37 | { 38 | await this._emulatorControl.ViewModel.StopAsync(); 39 | } 40 | 41 | [Guid("43F4976D-7ACE-49B8-A177-991E323B74E9")] 42 | internal class Pane : ToolkitToolWindowPane 43 | { 44 | public Pane() 45 | { 46 | BitmapImageMoniker = KnownMonikers.ToolWindow; 47 | } 48 | 49 | public event EventHandler Closing; 50 | 51 | protected override void OnClose() 52 | { 53 | Closing?.Invoke(this, EventArgs.Empty); 54 | base.OnClose(); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("VsAndroidEm")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("VsAndroidEm")] 13 | [assembly: AssemblyCopyright("")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // Version information for an assembly consists of the following four values: 23 | // 24 | // Major Version 25 | // Minor Version 26 | // Build Number 27 | // Revision 28 | // 29 | // You can specify all the values or you can default the Build and Revision Numbers 30 | // by using the '*' as shown below: 31 | // [assembly: AssemblyVersion("1.0.*")] 32 | [assembly: AssemblyVersion("1.0.0.0")] 33 | [assembly: AssemblyFileVersion("1.0.0.0")] 34 | -------------------------------------------------------------------------------- /src/Resources/SettingsPanel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adospace/vs-android-emulator/04f6df5b575e6f31a0d69f2a155b3b8306d9833a/src/Resources/SettingsPanel.png -------------------------------------------------------------------------------- /src/Resources/Stop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adospace/vs-android-emulator/04f6df5b575e6f31a0d69f2a155b3b8306d9833a/src/Resources/Stop.png -------------------------------------------------------------------------------- /src/Resources/StopOutline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adospace/vs-android-emulator/04f6df5b575e6f31a0d69f2a155b3b8306d9833a/src/Resources/StopOutline.png -------------------------------------------------------------------------------- /src/ShowToolWindowCommand.cs: -------------------------------------------------------------------------------- 1 | using Community.VisualStudio.Toolkit; 2 | using CommunityToolkit.Mvvm.Messaging; 3 | using Microsoft.VisualStudio.Shell; 4 | using Microsoft.VisualStudio.Text; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace VsAndroidEm; 12 | 13 | [Command(PackageIds.ShowToolWindowCommand)] 14 | internal class ShowToolWindowCommand : BaseCommand 15 | { 16 | protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) 17 | { 18 | await EmulatorWindow.ShowAsync(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/VSCommandTable.cs: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------------------ 2 | // 3 | // This file was generated by VSIX Synchronizer 4 | // 5 | // ------------------------------------------------------------------------------ 6 | namespace VsAndroidEm 7 | { 8 | using System; 9 | 10 | /// 11 | /// Helper class that exposes all GUIDs used across VS Package. 12 | /// 13 | internal sealed partial class PackageGuids 14 | { 15 | public const string VsAndroidEmString = "665a0c37-e208-4139-adbc-b5a36e1ad4ef"; 16 | public static Guid VsAndroidEm = new Guid(VsAndroidEmString); 17 | } 18 | /// 19 | /// Helper class that encapsulates all CommandIDs uses across VS Package. 20 | /// 21 | internal sealed partial class PackageIds 22 | { 23 | public const int ShowToolWindowCommand = 0x0100; 24 | } 25 | } -------------------------------------------------------------------------------- /src/VSCommandTable.vsct: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/VsAndroidEm.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 5 | latest 6 | 7 | 8 | 9 | Debug 10 | AnyCPU 11 | 2.0 12 | {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 13 | {519A84F0-9F82-4345-99AA-F1C0DE155B40} 14 | Library 15 | Properties 16 | VsAndroidEm 17 | VsAndroidEm 18 | v4.8 19 | true 20 | true 21 | true 22 | false 23 | false 24 | true 25 | true 26 | Program 27 | $(DevEnvDir)devenv.exe 28 | /rootsuffix Exp 29 | 30 | 31 | true 32 | full 33 | false 34 | bin\Debug\ 35 | DEBUG;TRACE 36 | prompt 37 | 4 38 | 39 | 40 | pdbonly 41 | true 42 | bin\Release\ 43 | TRACE 44 | prompt 45 | 4 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | EmulatorControl.xaml 54 | 55 | 56 | 57 | 58 | 59 | UserControl 60 | 61 | 62 | EmulatorViewer.cs 63 | 64 | 65 | 66 | 67 | 68 | True 69 | True 70 | source.extension.vsixmanifest 71 | 72 | 73 | 74 | True 75 | True 76 | VSCommandTable.vsct 77 | 78 | 79 | 80 | 81 | 82 | Designer 83 | VsixManifestGenerator 84 | source.extension.cs 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 3.6.4 104 | 105 | 106 | 107 | compile; build; native; contentfiles; analyzers; buildtransitive 108 | 109 | 110 | 8.2.1 111 | 112 | 113 | runtime; build; native; contentfiles; analyzers; buildtransitive 114 | all 115 | 116 | 117 | 118 | 119 | Menus.ctmenu 120 | VsctGenerator 121 | VSCommandTable.cs 122 | 123 | 124 | 125 | 126 | Designer 127 | MSBuild:Compile 128 | 129 | 130 | 131 | 132 | EmulatorViewer.cs 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 153 | -------------------------------------------------------------------------------- /src/VsAndroidEm.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.33711.374 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VsAndroidEm", "VsAndroidEm.csproj", "{519A84F0-9F82-4345-99AA-F1C0DE155B40}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|arm64 = Debug|arm64 12 | Debug|x86 = Debug|x86 13 | Release|Any CPU = Release|Any CPU 14 | Release|arm64 = Release|arm64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|arm64.ActiveCfg = Debug|arm64 21 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|arm64.Build.0 = Debug|arm64 22 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|x86.ActiveCfg = Debug|x86 23 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Debug|x86.Build.0 = Debug|x86 24 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|arm64.ActiveCfg = Release|arm64 27 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|arm64.Build.0 = Release|arm64 28 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|x86.ActiveCfg = Release|x86 29 | {519A84F0-9F82-4345-99AA-F1C0DE155B40}.Release|x86.Build.0 = Release|x86 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {79BF4C9F-5BD7-4680-974C-A97DC23C066F} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /src/VsAndroidEmPackage.cs: -------------------------------------------------------------------------------- 1 | using Community.VisualStudio.Toolkit; 2 | using Microsoft.VisualStudio; 3 | using Microsoft.VisualStudio.Shell; 4 | using Microsoft.VisualStudio.Shell.Interop; 5 | using System; 6 | using System.Globalization; 7 | using System.Runtime.InteropServices; 8 | using System.Threading; 9 | using Task = System.Threading.Tasks.Task; 10 | 11 | namespace VsAndroidEm 12 | { 13 | /// 14 | /// This is the class that implements the package exposed by this assembly. 15 | /// 16 | /// 17 | /// 18 | /// The minimum requirement for a class to be considered a valid package for Visual Studio 19 | /// is to implement the IVsPackage interface and register itself with the shell. 20 | /// This package uses the helper classes defined inside the Managed Package Framework (MPF) 21 | /// to do it: it derives from the Package class that provides the implementation of the 22 | /// IVsPackage interface and uses the registration attributes defined in the framework to 23 | /// register itself and its components with the shell. These attributes tell the pkgdef creation 24 | /// utility what data to put into .pkgdef file. 25 | /// 26 | /// 27 | /// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file. 28 | /// 29 | /// 30 | [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] 31 | [InstalledProductRegistration(Vsix.Name, Vsix.Description, Vsix.Version)] 32 | [ProvideToolWindow(typeof(EmulatorWindow.Pane), Style = VsDockStyle.Tabbed, Window = WindowGuids.SolutionExplorer)] 33 | [ProvideToolWindowVisibility(typeof(EmulatorWindow.Pane), VSConstants.UICONTEXT.SolutionHasSingleProject_string)] 34 | [ProvideToolWindowVisibility(typeof(EmulatorWindow.Pane), VSConstants.UICONTEXT.SolutionHasMultipleProjects_string)] 35 | [ProvideToolWindowVisibility(typeof(EmulatorWindow.Pane), VSConstants.UICONTEXT.NoSolution_string)] 36 | [ProvideToolWindowVisibility(typeof(EmulatorWindow.Pane), VSConstants.UICONTEXT.EmptySolution_string)] 37 | 38 | [ProvideMenuResource("Menus.ctmenu", 1)] 39 | [Guid(PackageGuids.VsAndroidEmString)] 40 | public sealed class VsAndroidEmPackage : ToolkitPackage 41 | { 42 | protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress progress) 43 | { 44 | await this.RegisterCommandsAsync(); 45 | 46 | this.RegisterToolWindows(); 47 | 48 | //await JoinableTaskFactory.SwitchToMainThreadAsync(); 49 | 50 | //IVsActivityLog log = (IVsActivityLog)(await GetServiceAsync(typeof(SVsActivityLog))); 51 | //if (log == null) return; 52 | 53 | //int hr = log.LogEntry((UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, 54 | // this.ToString(), 55 | // string.Format(CultureInfo.CurrentCulture, 56 | // "Called for: {0}", this.ToString())); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Win32API.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using System.Security.Policy; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows; 10 | 11 | namespace VsAndroidEm 12 | { 13 | public class Win32API 14 | { 15 | [DllImport("User32.dll")] 16 | internal static extern IntPtr SetParent(IntPtr hwc, IntPtr hwp); 17 | 18 | [DllImport("user32.dll", SetLastError = true)] 19 | internal static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); 20 | 21 | public const uint WM_CLOSE = 0x0010; 22 | 23 | /// 24 | /// This static method is required because legacy OSes do not support SetWindowLongPtr 25 | /// 26 | internal static IntPtr SetWindowLongPtr(HandleRef hWnd, int nIndex, IntPtr dwNewLong) 27 | { 28 | if (IntPtr.Size == 8) 29 | return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); 30 | else 31 | return new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong.ToInt32())); 32 | } 33 | 34 | [DllImport("user32.dll", EntryPoint = "SetWindowLong")] 35 | private static extern int SetWindowLong32(HandleRef hWnd, int nIndex, int dwNewLong); 36 | 37 | [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] 38 | private static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, IntPtr dwNewLong); 39 | 40 | [DllImport("user32.dll", EntryPoint = "GetWindowLong")] 41 | private static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex); 42 | 43 | [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")] 44 | private static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); 45 | 46 | /// 47 | /// This static method is required because Win32 does not support GetWindowLongPtr directly 48 | /// 49 | internal static IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex) 50 | { 51 | if (IntPtr.Size == 8) 52 | return GetWindowLongPtr64(hWnd, nIndex); 53 | else 54 | return GetWindowLongPtr32(hWnd, nIndex); 55 | } 56 | 57 | [DllImport("user32.dll")] 58 | [return: MarshalAs(UnmanagedType.Bool)] 59 | internal static extern bool SetForegroundWindow(IntPtr hWnd); 60 | 61 | [DllImport("user32.dll", SetLastError = true)] 62 | internal static extern bool BringWindowToTop(IntPtr hWnd); 63 | 64 | [DllImport("user32.dll", SetLastError = true)] 65 | internal static extern bool BringWindowToTop(HandleRef hWnd); 66 | 67 | internal const int GWL_STYLE = -16; 68 | internal const int GWL_EXSTYLE = -20; 69 | 70 | [DllImport("user32.dll", SetLastError = true)] 71 | public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); 72 | 73 | [DllImport("user32.dll", SetLastError = true)] 74 | public static extern int GetWindowLong(IntPtr hWnd, int nIndex); 75 | 76 | //const int GWL_STYLE = -16; 77 | //const int WS_CHILD = 0x40000000; 78 | //const int WS_BORDER = 0x00800000; 79 | //const int WS_DLGFRAME = 0x00400000; 80 | //const int WS_CAPTION = WS_BORDER | WS_DLGFRAME; 81 | 82 | [Flags] 83 | internal enum WindowStyles : uint 84 | { 85 | WS_OVERLAPPED = 0x00000000, 86 | WS_POPUP = 0x80000000, 87 | WS_CHILD = 0x40000000, 88 | WS_MINIMIZE = 0x20000000, 89 | WS_VISIBLE = 0x10000000, 90 | WS_DISABLED = 0x08000000, 91 | WS_CLIPSIBLINGS = 0x04000000, 92 | WS_CLIPCHILDREN = 0x02000000, 93 | WS_MAXIMIZE = 0x01000000, 94 | WS_BORDER = 0x00800000, 95 | WS_DLGFRAME = 0x00400000, 96 | WS_VSCROLL = 0x00200000, 97 | WS_HSCROLL = 0x00100000, 98 | WS_SYSMENU = 0x00080000, 99 | WS_THICKFRAME = 0x00040000, 100 | WS_GROUP = 0x00020000, 101 | WS_TABSTOP = 0x00010000, 102 | 103 | WS_MINIMIZEBOX = 0x00020000, 104 | WS_MAXIMIZEBOX = 0x00010000, 105 | 106 | WS_CAPTION = WS_BORDER | WS_DLGFRAME, 107 | WS_TILED = WS_OVERLAPPED, 108 | WS_ICONIC = WS_MINIMIZE, 109 | WS_SIZEBOX = WS_THICKFRAME, 110 | WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, 111 | 112 | WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, 113 | WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU, 114 | WS_CHILDWINDOW = WS_CHILD, 115 | 116 | //Extended Window Styles 117 | 118 | WS_EX_DLGMODALFRAME = 0x00000001, 119 | WS_EX_NOPARENTNOTIFY = 0x00000004, 120 | WS_EX_TOPMOST = 0x00000008, 121 | WS_EX_ACCEPTFILES = 0x00000010, 122 | WS_EX_TRANSPARENT = 0x00000020, 123 | 124 | //#if(WINVER >= 0x0400) 125 | 126 | WS_EX_MDICHILD = 0x00000040, 127 | WS_EX_TOOLWINDOW = 0x00000080, 128 | WS_EX_WINDOWEDGE = 0x00000100, 129 | WS_EX_CLIENTEDGE = 0x00000200, 130 | WS_EX_CONTEXTHELP = 0x00000400, 131 | 132 | WS_EX_RIGHT = 0x00001000, 133 | WS_EX_LEFT = 0x00000000, 134 | WS_EX_RTLREADING = 0x00002000, 135 | WS_EX_LTRREADING = 0x00000000, 136 | WS_EX_LEFTSCROLLBAR = 0x00004000, 137 | WS_EX_RIGHTSCROLLBAR = 0x00000000, 138 | 139 | WS_EX_CONTROLPARENT = 0x00010000, 140 | WS_EX_STATICEDGE = 0x00020000, 141 | WS_EX_APPWINDOW = 0x00040000, 142 | 143 | WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE), 144 | WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST), 145 | //#endif /* WINVER >= 0x0400 */ 146 | 147 | //#if(WIN32WINNT >= 0x0500) 148 | 149 | WS_EX_LAYERED = 0x00080000, 150 | //#endif /* WIN32WINNT >= 0x0500 */ 151 | 152 | //#if(WINVER >= 0x0500) 153 | 154 | WS_EX_NOINHERITLAYOUT = 0x00100000, // Disable inheritence of mirroring by children 155 | WS_EX_LAYOUTRTL = 0x00400000, // Right to left mirroring 156 | //#endif /* WINVER >= 0x0500 */ 157 | 158 | //#if(WIN32WINNT >= 0x0500) 159 | 160 | WS_EX_COMPOSITED = 0x02000000, 161 | WS_EX_NOACTIVATE = 0x08000000 162 | //#endif /* WIN32WINNT >= 0x0500 */ 163 | } 164 | 165 | 166 | [DllImport("user32.dll")] 167 | public static extern IntPtr FindWindowEx(IntPtr parentWindow, IntPtr previousChildWindow, string windowClass, string windowTitle); 168 | 169 | [DllImport("user32.dll")] 170 | private static extern IntPtr GetWindowThreadProcessId(IntPtr window, out int process); 171 | 172 | public const int SW_HIDE = 0; 173 | public const int SW_SHOW = 5; 174 | 175 | [DllImport("User32")] 176 | public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); 177 | 178 | public static IntPtr[] GetProcessWindows(int process) 179 | { 180 | IntPtr[] apRet = (new IntPtr[256]); 181 | int iCount = 0; 182 | IntPtr pLast = IntPtr.Zero; 183 | do 184 | { 185 | pLast = FindWindowEx(IntPtr.Zero, pLast, null, null); 186 | int iProcess_; 187 | GetWindowThreadProcessId(pLast, out iProcess_); 188 | if (iProcess_ == process) apRet[iCount++] = pLast; 189 | } while (pLast != IntPtr.Zero); 190 | System.Array.Resize(ref apRet, iCount); 191 | return apRet; 192 | } 193 | 194 | delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); 195 | 196 | [DllImport("user32.dll")] 197 | static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, 198 | IntPtr lParam); 199 | 200 | public static IEnumerable EnumerateProcessWindowHandles(int processId) 201 | { 202 | var handles = new List(); 203 | 204 | foreach (ProcessThread thread in Process.GetProcessById(processId).Threads) 205 | EnumThreadWindows(thread.Id, 206 | (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero); 207 | 208 | return handles; 209 | } 210 | 211 | [DllImport("user32.dll")] 212 | public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); 213 | 214 | public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); 215 | 216 | public static IEnumerable GetAllChildWindows(IntPtr hWndParent) 217 | { 218 | var childHandles = new List(); 219 | 220 | EnumChildWindows(hWndParent, (hWnd, lParam) => 221 | { 222 | childHandles.Add(hWnd); 223 | return true; 224 | }, IntPtr.Zero); 225 | 226 | return childHandles; 227 | } 228 | 229 | [DllImport("user32.dll")] 230 | [return: MarshalAs(UnmanagedType.Bool)] 231 | public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); 232 | 233 | [DllImport("user32.dll", SetLastError = true)] 234 | public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect); 235 | 236 | [DllImport("user32.dll", SetLastError = true)] 237 | [return: MarshalAs(UnmanagedType.Bool)] 238 | public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); 239 | 240 | [DllImport("user32.dll")] 241 | public static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, IntPtr hrgnUpdate, RedrawWindowFlags flags); 242 | 243 | [Flags()] 244 | public enum RedrawWindowFlags : uint 245 | { 246 | Invalidate = 0x1, 247 | InternalPaint = 0x2, 248 | Erase = 0x4, 249 | Validate = 0x8, 250 | NoInternalPaint = 0x10, 251 | NoErase = 0x20, 252 | NoChildren = 0x40, 253 | AllChildren = 0x80, 254 | UpdateNow = 0x100, 255 | EraseNow = 0x200, 256 | Frame = 0x400, 257 | NoFrame = 0x800 258 | } 259 | 260 | [StructLayout(LayoutKind.Sequential)] 261 | public struct RECT 262 | { 263 | public int Left; // x position of upper-left corner 264 | public int Top; // y position of upper-left corner 265 | public int Right; // x position of lower-right corner 266 | public int Bottom; // y position of lower-right corner 267 | } 268 | 269 | [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] 270 | public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, 271 | ref Size psize, IntPtr hdcSrc, ref Point pprSrc, int crKey, 272 | ref BLENDFUNCTION pblend, BlendFlags dwFlags); 273 | 274 | [StructLayout(LayoutKind.Sequential, Pack = 1)] 275 | public struct BLENDFUNCTION 276 | { 277 | public byte BlendOp; 278 | public byte BlendFlags; 279 | public byte SourceConstantAlpha; 280 | public byte AlphaFormat; 281 | } 282 | 283 | public enum BlendFlags : uint 284 | { 285 | None = 0x00, 286 | ULW_COLORKEY = 0x01, 287 | ULW_ALPHA = 0x02, 288 | ULW_OPAQUE = 0x04 289 | } 290 | 291 | // PInvoke declarations 292 | [DllImport("user32.dll")] 293 | public static extern int GetSystemMetrics(SystemMetric smIndex); 294 | 295 | public enum SystemMetric 296 | { 297 | SM_CYCAPTION = 4, 298 | SM_CXBORDER = 5, 299 | SM_CYBORDER = 6, 300 | } 301 | 302 | [DllImport("user32.dll", SetLastError = true)] 303 | public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags); 304 | 305 | public enum SetWindowPosFlags : uint 306 | { 307 | IgnoreMove = 0x0002, 308 | NoZOrder = 0x0004, 309 | NoRedraw = 0x0008, 310 | NoActivate = 0x0010, 311 | DrawFrame = 0x0020, 312 | FrameChanged = 0x0020, 313 | ShowWindow = 0x0040, 314 | HideWindow = 0x0080, 315 | NoCopyBits = 0x0100, 316 | NoOwnerZOrder = 0x0200, 317 | NoSendChanging = 0x0400, 318 | } 319 | 320 | 321 | [DllImport("user32.dll")] 322 | public static extern bool UpdateWindow(IntPtr hWnd); 323 | 324 | [DllImport("user32.dll", CharSet = CharSet.Unicode)] 325 | public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); 326 | 327 | [DllImport("kernel32.dll")] 328 | public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId); 329 | 330 | [DllImport("kernel32.dll", SetLastError = true)] 331 | public static extern bool CloseHandle(IntPtr hObject); 332 | 333 | [Flags] 334 | public enum ProcessAccessFlags : uint 335 | { 336 | QueryLimitedInformation = 0x1000 337 | } 338 | 339 | public static bool CheckProcessIsRunning(int processId) 340 | { 341 | // Open the process with query limited information rights and get a handle to the process 342 | IntPtr processHandle = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, processId); 343 | 344 | if (processHandle == IntPtr.Zero) 345 | { 346 | return false; 347 | } 348 | 349 | CloseHandle(processHandle); 350 | return true; 351 | } 352 | 353 | [DllImport("kernel32.dll")] 354 | public static extern uint GetLastError(); 355 | 356 | 357 | [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 358 | public static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, 359 | uint dwLanguageId, StringBuilder lpBuffer, uint nSize, IntPtr Arguments); 360 | 361 | public const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; 362 | public const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; 363 | 364 | [DllImport("user32.dll")] 365 | [return: MarshalAs(UnmanagedType.Bool)] 366 | public static extern bool IsWindowVisible(IntPtr hWnd); 367 | } 368 | } 369 | -------------------------------------------------------------------------------- /src/source.extension.cs: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------------------ 2 | // 3 | // This file was generated by VSIX Synchronizer 4 | // 5 | // ------------------------------------------------------------------------------ 6 | namespace VsAndroidEm 7 | { 8 | internal sealed partial class Vsix 9 | { 10 | public const string Id = "VsAndroidEm.5dfcfa73-0d82-4b24-9c01-479eaa271e61"; 11 | public const string Name = "VsAndroidEm"; 12 | public const string Description = @"This extension embeds the Android emulator directly inside a tool window of Visual Studio. It allows to switch between multiple running emulators, show/hide their toolbar, stop or shutdown them."; 13 | public const string Language = "en-US"; 14 | public const string Version = "1.10"; 15 | public const string Author = "Adolfo Marinucci"; 16 | public const string Tags = "android emulator"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/source.extension.vsixmanifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | VsAndroidEm 6 | This extension embeds the Android emulator directly inside a tool window of Visual Studio. It allows to switch between multiple running emulators, show/hide their toolbar, stop or shutdown them. 7 | https://github.com/adospace/vs-android-emulator 8 | android emulator 9 | 10 | 11 | 12 | amd64 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------