- How to: Debug Windows Service Applications
- To debug a service
- Debugging Tips for Windows Services
- How to: Run a Windows Service as a console application
- Debugging Tools for Windows (WinDbg, KD, CDB, NTSD)
- Install Debugging Tools for Windows
- Get started with Windows Debugging
- Debugging environments
- Windows debuggers
- Symbols and symbol files
- Blue screens and crash dump files
- Tools and utilities
- Additional documentation
- Функции и отладка в режиме разработчика Developer Mode features and debugging
- Дополнительные возможности режима разработчика Additional Developer Mode features
- Портал устройств Device Portal
- Загрузка неопубликованных приложений Sideload apps
- SSH SSH
- Предупреждения об использовании SSH Caveats for SSH usage
- Обнаружение устройства Device Discovery
- Оптимизация для проводника Windows, удаленного рабочего стола и PowerShell (только на ПК) Optimizations for Windows Explorer, Remote Desktop, and PowerShell (Desktop only)
- Примечания Notes
- Сбой установки пакета режима разработчика Failure to install Developer Mode package
- Сбой поиска пакета Failed to locate the package
- Сбой установки пакета Failed to install the package
- Использование групповых политик или разделов реестра для подготовки устройства Use group policies or registry keys to enable a device
- Обновление устройства с Windows 8.1 до Windows 10 Upgrade your device from Windows 8.1 to Windows 10
How to: Debug Windows Service Applications
A service must be run from within the context of the Services Control Manager rather than from within Visual Studio. For this reason, debugging a service is not as straightforward as debugging other Visual Studio application types. To debug a service, you must start the service and then attach a debugger to the process in which it is running. You can then debug your application by using all of the standard debugging functionality of Visual Studio.
You should not attach to a process unless you know what the process is and understand the consequences of attaching to and possibly killing that process. For example, if you attach to the WinLogon process and then stop debugging, the system will halt because it can’t operate without WinLogon.
You can attach the debugger only to a running service. The attachment process interrupts the current functioning of your service; it doesn’t actually stop or pause the service’s processing. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.
After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you’ve set. You can later remove this dummy service after debugging is successful.
This article covers debugging a service that’s running on the local computer, but you can also debug Windows Services that are running on a remote computer. See Remote Debugging.
Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all attempts to start a service. For more information, see Troubleshooting: Debugging Windows Services.
To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that are being debugged. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the same folder as the executable or library, and the debugger loads them automatically. If you are debugging a service that you didn’t build, you should first find symbols for the service and make sure they can be found by the debugger. See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. If you’re debugging a system process or want to have symbols for system calls in your services, you should add the Microsoft Symbol Servers. See Debugging Symbols.
To debug a service
Build your service in the Debug configuration.
Install your service. For more information, see How to: Install and Uninstall Services.
Start your service, either from Services Control Manager, Server Explorer, or from code. For more information, see How to: Start Services.
Start Visual Studio with administrative credentials so you can attach to system processes.
(Optional) On the Visual Studio menu bar, choose Tools, Options. In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button.
On the menu bar, choose Attach to Process from the Debug or Tools menu. (Keyboard: Ctrl+Alt+P)
The Processes dialog box appears.
Select the Show processes from all users check box.
In the Available Processes section, choose the process for your service, and then choose Attach.
The process will have the same name as the executable file for your service.
The Attach to Process dialog box appears.
Choose the appropriate options, and then choose OK to close the dialog box.
You are now in debug mode.
Set any breakpoints you want to use in your code.
Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints. For more information about running the Services Control Manager, see How to: Start Services. Also, see Troubleshooting: Debugging Windows Services.
Debugging Tips for Windows Services
Attaching to the service’s process allows you to debug most, but not all, the code for that service. For example, because the service has already been started, you cannot debug the code in the service’s OnStart method or the code in the Main method that is used to load the service this way. One way to work around this limitation is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this dummy service to load the service process. Once the temporary service has started the process, you can use the Debug menu in Visual Studio to attach to the service process.
Try adding calls to the Sleep method to delay action until you’re able to attach to the process.
Try changing the program to a regular console application. To do this, rewrite the Main method as follows so it can run both as a Windows Service and as a console application, depending on how it’s started.
How to: Run a Windows Service as a console application
Add a method to your service that runs the OnStart and OnStop methods:
Rewrite the Main method as follows:
In the Application tab of the project’s properties, set the Output type to Console Application.
Choose Start Debugging (F5).
To run the program as a Windows Service again, install it and start it as usual for a Windows Service. It’s not necessary to reverse these changes.
In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the Windows debugger. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.
Debugging Tools for Windows (WinDbg, KD, CDB, NTSD)
Start here for an overview of Debugging Tools for Windows. This tool set includes WinDbg and other debuggers.
Install Debugging Tools for Windows
You can get Debugging Tools for Windows as part of a development kit or as a standalone tool set:
As part of the WDK
Debugging Tools for Windows is included in the Windows Driver Kit (WDK). To get the WDK, see Download the Windows Driver Kit (WDK).
As part of the Windows SDK
Debugging Tools for Windows is included in the Windows Software Development Kit (SDK). To download the installer or an ISO image, see Windows 10 SDK on Windows Dev Center.
As a standalone tool set
You can install the Debugging Tools for Windows alone, without the Windows SDK or WDK, by starting installation of the Windows SDK and then selecting only Debugging Tools for Windows in the list of features to install (and clearing the selection of all other features). To download the installer or an ISO image, see Windows 10 SDK on Windows Dev Center.
Get started with Windows Debugging
To get started with Windows debugging, see Getting Started with Windows Debugging.
To get started with debugging kernel-mode drivers, see Debug Universal Drivers — Step by Step Lab (Echo Kernel-Mode). This is a step-by-step lab that shows how to use WinDbg to debug Echo, a sample driver that uses the Kernel-Mode Driver Framework (KMDF).
Debugging environments
If your computer has Visual Studio and the WDK installed, then you have six available debugging environments. For descriptions of these environments, see Debugging Environments.
All of these debugging environments provide user interfaces for the same underlying debugging engine, which is implemented in the Windows Symbolic Debugger Engine (Dbgeng.dll). This debugging engine is also called the Windows debugger, and the six debugging environments are collectively called the Windows debuggers.
Visual Studio includes its own debugging environment and debugging engine, which together are called the Visual Studio debugger. For information on debugging in Visual Studio, see Debugging in Visual Studio. For debugging managed code, such as C#, using the Visual Studio debugger is often the easiest way to get started.
Windows debuggers
The Windows debuggers can run on x86-based, x64-based, or ARM-based processors, and they can debug code that is running on those same architectures. Sometimes the debugger and the code being debugged run on the same computer, but other times the debugger and the code being debugged run on separate computers. In either case, the computer that is running the debugger is called the host computer, and the computer that is being debugged is called the target computer. The Windows debuggers support the following versions of Windows for both the host and target computers.
- WindowsВ 10 and Windows ServerВ 2016
- WindowsВ 8.1 and Windows ServerВ 2012В R2
- WindowsВ 8 and Windows ServerВ 2012
- WindowsВ 7 and Windows ServerВ 2008В R2
Symbols and symbol files
Symbol files store a variety of data that are not required when running the executable binaries, but symbol files are very useful when debugging code. For more information about creating and using symbol files, see Symbols for Windows debugging (WinDbg, KD, CDB, NTSD).
Blue screens and crash dump files
If Windows stops working and displays a blue screen, the computer has shut down abruptly to protect itself from data loss and displays a bug check code. For more information, see Bug Checks (Blue Screens). You analyze crash dump files that are created when Windows shuts down by using WinDbg and other Windows debuggers. For more information, see Crash dump analysis using the Windows debuggers (WinDbg).
Tools and utilities
In addition to the debuggers, Debugging Tools for Windows includes a set of tools that are useful for debugging. For a full list of the tools, see Tools Included in Debugging Tools for Windows.
Additional documentation
For additional information related to Debugging Tools for Windows, see Debugging Resources. For information on what’s new in Windows 10, see Debugging Tools for Windows: New for Windows 10.
Функции и отладка в режиме разработчика Developer Mode features and debugging
Если вы только заинтересованы в основах установки режима разработчика для приложения, можно просто выполнить инструкции, описанные в разделе о том, как включить разработку для устройства , чтобы приступить к работе. If you’re just interested in the basics of installing developer mode on your app, you can just follow the instructions outlined in enable your device for development to get started. в этой статье рассматриваются расширенные возможности режима разработчика, режима разработчика в предыдущих версиях Windows 10 и сбои при отладке в установке в режиме разработчика. this article covers advanced features of developer mode, developer mode on previous versions of Windows 10, and debugging failures in Developer Mode installation.
Дополнительные возможности режима разработчика Additional Developer Mode features
Для каждого семейства устройств могут быть доступны дополнительные функциональные возможности разработчика. For each device family, additional developer features might be available. Эти функциональные возможности доступны только в том случае, если режим разработчика включен на устройстве, и могут зависеть от версии ОС. These features are available only when Developer Mode is enabled on the device, and might vary depending on your OS version.
На этом рисунке представлены возможности разработчика для Windows 10. This image shows developer features for Windows 10:
Портал устройств Device Portal
Дополнительные сведения о портале устройств см. в разделе Обзор портала устройства с Windows. To learn more about Device Portal, see Windows Device Portal overview.
Конкретные инструкции по настройке устройства см. в следующих разделах: For device specific setup instructions, see:
Если у вас возникают проблемы с включением Режима разработчика или порталом устройств, посетите форум Известные проблемы, чтобы найти способы устранения этих проблем, или изучите раздел Сбой установки пакета режима разработчика, чтобы получить дополнительные сведений и узнать больше о том, какие обновления WSUS помогут разблокировать пакет режима разработчика. If you encounter problems enabling Developer Mode or Device Portal, see the Known Issues forum to find workarounds for these issues, or visit Failure to install the Developer Mode package for additional details and which WSUS KBs to allow in order to unblock the Developer Mode package.
Загрузка неопубликованных приложений Sideload apps
Начиная с последнего обновления Windows 10 этот параметр не будет отображаться, так как по умолчанию включена поддержка загрузки неопубликованных приложений. As of the latest Windows 10 update, this setting won’t be visible, as sideloading is enabled by default. Если вы используете предыдущую версию Windows 10, параметры по умолчанию разрешат запускать приложения только из Microsoft Store. Чтобы устанавливать приложения из сторонних источников, вам нужно включить загрузку неопубликованных приложений. If you are on a previous version of Windows 10, your default settlings will only permit you to run apps from the Microsoft Store, and you must enable Sideloading to install apps from non-Microsoft sources.
Функция Загрузка неопубликованных приложений обычно используется компаниями или учебными заведениями, которым необходимо устанавливать свои приложения на управляемых устройствах, не используя Microsoft Store. Она также может потребоваться пользователям, которые запускают приложения не от корпорации Майкрософт. The Sideload apps setting is typically used by companies or schools that need to install custom apps on managed devices without going through the Microsoft Store, or anyone else who needs to run apps from non-Microsoft sources. В этом случае организации обычно применяют политику, отключающую Приложения UWP, как показано выше на изображении страницы параметров. In this case, it’s common for the organization to enforce a policy that disables the UWP apps setting, as shown previously in the image of the settings page. Кроме того, организация предоставляет необходимый сертификат и расположение установки для загрузки неопубликованных приложений. The organization also provides the required certificate and install location to sideload apps. Дополнительные сведения см. в статьях TechNet Загрузка неопубликованных приложений в Windows 10 и Основы Microsoft Intune. For more info, see the TechNet articles Sideload apps in Windows 10 and Microsoft Intune fundamentals.
Сведения, предназначенные для определенных семейств устройств Device family specific info
Для семейства настольных устройств Вы можете установить пакет приложения (APPX-файл) и любой сертификат, необходимый для запуска приложения, выполнив сценарий Windows PowerShell, созданный с использованием пакета (Add-AppDevPackage.ps1). On the desktop device family: You can install an app package (.appx) and any certificate that is needed to run the app by running the Windows PowerShell script that is created with the package («Add-AppDevPackage.ps1»). Дополнительные сведения см. в разделе Формирование пакетов приложений UWP. For more info, see Packaging UWP apps.
Для семейства мобильных устройств Если необходимый сертификат уже установлен, вы можете коснуться файла, чтобы установить любой APPX-файл, отправленный вам по электронной почте или на SD-карте. On the mobile device family: If the required certificate is already installed, you can tap the file to install any .appx sent to you via email or on an SD card.
Загрузка неопубликованных приложений — более безопасный вариант, чем Режим разработчика, так как вы не сможете устанавливать на устройство приложения без доверенного сертификата. Sideload apps is a more secure option than Developer Mode because you cannot install apps on the device without a trusted certificate.
При загрузке неопубликованных приложений по-прежнему необходимо следить, чтобы они были получены из надежных источников. If you sideload apps, you should still only install apps from trusted sources. При установке неопубликованного приложения, еще не сертифицированного Microsoft Store, вы соглашаетесь, что получили все необходимые права для загрузки этого приложения и несете всю ответственность за любые убытки, которые могут возникнуть в результате установки и запуска приложения. When you install a sideloaded app that has not been certified by the Microsoft Store, you are agreeing that you have obtained all rights necessary to sideload the app and that you are solely responsible for any harm that results from installing and running the app. См. раздел «Windows > Microsoft Store» данного заявления о конфиденциальности. See the Windows > Microsoft Store section of this privacy statement.
SSH SSH
Службы SSH включаются при включении параметра Обнаружение устройств на устройстве. SSH services are enabled when you enable Device Discovery on your device. Они используются, если устройство является целью удаленного развертывания для приложений UWP. This is used when your device is a remote deployment target for UWP applications. Службы называются SSH Server Broker и SSH Server Proxy. The names of the services are ‘SSH Server Broker’ and ‘SSH Server Proxy’.
Это реализация OpenSSH (не Microsoft), которую можно найти на GitHub. This is not Microsoft’s OpenSSH implementation, which you can find on GitHub.
Чтобы воспользоваться преимуществами служб SSH, можно включить функцию обнаружения устройств для разрешения связывания с помощью PIN-кода. In order to take advantage of the SSH services, you can enable device discovery to allow pin pairing. Если планируется запускать другую службу SSH, можно настроить ее с другим портом или отключить службы SSH режима разработчика. If you intend to run another SSH service, you can set this up on a different port or turn off the Developer Mode SSH services. Чтобы отключить службы SSH, отключите функцию Обнаружение устройств. To turn off the SSH services, turn off Device Discovery.
Вход с помощью SSH осуществляется с учетной записью DevToolsUser с соответствующим паролем для прохождения аутентификации. SSH login is done via the «DevToolsUser» account, which accepts a password for authentication. Этот пароль — это PIN-код, отображаемый на устройстве после нажатия кнопки «Связать», и он действует, только пока отображается PIN-код. This password is the PIN displayed on the device after pressing the device discovery «Pair» button, and is only valid while the PIN is displayed. Подсистема SFTP также включается для ручного управления папкой DevelopmentFiles, в которую устанавливаются файлы свободного развертывания из Visual Studio. An SFTP subsystem is also enabled, for manual management of the DevelopmentFiles folder where loose file deployments are installed from Visual Studio.
Предупреждения об использовании SSH Caveats for SSH usage
Сервер SSH, используемый в Windows, еще не удовлетворяет требованиям протокола, поэтому использование клиента SFTP или SSH может потребовать дополнительной настройки. The existing SSH server used in Windows is not yet protocol compliant, so using an SFTP or SSH client may require special configuration. В частности, подсистема SFTP выполняется в версии 3 или более поздней версии, поэтому любой подключаемый клиент должен быть настроен таким образом, чтобы он смог работать со старым сервером. In particular, the SFTP subsystem runs at version 3 or less, so any connecting client should be configured to expect an old server. Сервер SSH на более старых устройствах использует ssh-dss для аутентификации с помощью открытого ключа, что не рекомендовалось при использовании OpenSSH. The SSH server on older devices uses ssh-dss for public key authentication, which OpenSSH has deprecated. Для подключения к таким устройствам клиент SSH необходимо вручную настроить для приема ssh-dss . To connect to such devices the SSH client must be manually configured to accept ssh-dss .
Обнаружение устройства Device Discovery
При включении обнаружения устройства вы разрешаете, чтобы устройство было видимым для других устройств в сети через mDNS. When you enable device discovery, you are allowing your device to be visible to other devices on the network through mDNS. Эта функция также позволяет получить ПИН-код сервера SSH для связывания с этим устройством нажатием кнопки Связать, отображающейся после включения обнаружения устройств. This feature also allows you to get the SSH PIN for pairing to this device by pressing the «Pair» button exposed once device discovery is enabled. Это окно для ПИН-кода должно отобразиться на экране, чтобы вы могли завершить первое развертывание Visual Studio на целевом устройстве. This PIN prompt must be displayed on the screen in order to complete your first Visual Studio deployment targeting the device.
Обнаружение устройства следует включать только в том случае, если устройство будет являться целью развертывания. You should enable device discovery only if you intend to make the device a deployment target. Например если вы используете портал устройств для развертывания приложения на телефоне для тестирования, необходимо включить функцию обнаружения устройств на телефоне, но не на компьютере разработчика. For example, if you use Device Portal to deploy an app to a phone for testing, you need to enable device discovery on the phone, but not on your development PC.
Оптимизация для проводника Windows, удаленного рабочего стола и PowerShell (только на ПК) Optimizations for Windows Explorer, Remote Desktop, and PowerShell (Desktop only)
Для семейства настольных устройств на странице параметров Для разработчиков имеются ссылки на параметры, которые можно использовать для оптимизации компьютера под задачи разработки. On the desktop device family, the For developers settings page has shortcuts to settings that you can use to optimize your PC for development tasks. Для каждого параметра можно установить флажок и нажать кнопку Применить или нажать ссылку Показать параметры, чтобы открыть страницу параметров для этого варианта. For each setting, you can select the checkbox and click Apply, or click the Show settings link to open the settings page for that option.
Примечания Notes
В ранних версиях Windows 10 Mobile в меню Параметры разработчика был параметр Аварийные дампы. In early versions of Windows 10 Mobile, a Crash Dumps option was present in the Developer Settings menu. Теперь он перемещен на портал устройств, чтобы его можно было использовать удаленно, а не только через USB-порт. This has been moved to Device Portal so that it can be used remotely rather than just over USB.
Существует ряд средств, которые вы можете использовать для развертывания приложения с компьютера с Windows 10 на мобильном устройстве с Windows 10. There are several tools you can use to deploy an app from a Windows 10 PC to a Windows 10 device. Оба устройства должны быть подключены к одной подсети с помощью проводного или беспроводного подключения или соединены друг с другом через USB. Both devices must be connected to the same subnet of the network by a wired or wireless connection, or they must be connected by USB. При использовании любого из указанных способов будет установлен только пакет приложения (.appx/.appxbundle); сертификаты установлены не будут. Both of the ways listed install only the app package (.appx/.appxbundle); they do not install certificates.
- Используйте средство развертывания приложений для Windows 10 (WinAppDeployCmd). Use the Windows 10 Application Deployment (WinAppDeployCmd) tool. Узнайте больше о средстве WinAppDeployCmd. Learn more about the WinAppDeployCmd tool.
- Вы можете использовать портал устройств для развертывания из браузера на мобильном устройстве с Windows 10 версии 1511 или более поздней версии. You can use Device Portal to deploy from your browser to a mobile device running Windows 10, Version 1511 or later. Используйте страницу Приложения портала устройств для отправки пакета приложения (APPX-файл) и установки его на устройство. Use the Apps page in Device Portal to upload an app package (.appx) and install it on the device.
Сбой установки пакета режима разработчика Failure to install Developer Mode package
Иногда из-за проблем с сетью или административных конфликтов пакет режима разработчика может установиться неправильно. Sometimes, due to network or administrative issues, Developer Mode won’t install correctly. Пакет режима разработчика требуется для удаленного развертывания на этом компьютере для включения SSH с помощью портала устройств из браузера или обнаружения устройств, но не для локальной разработки. The Developer Mode package is required for remote deployment to this PC — using Device Portal from a browser or Device Discovery to enable SSH — but not for local development. Даже столкнувшись с этими проблемами, вы все равно сможете развернуть приложение локально с помощью Visual Studio или с этого устройства на другом. Even if you encounter these issues, you can still deploy your app locally using Visual Studio, or from this device to another device.
Пути обхода этих проблем и другую информацию см. на форуме Известные проблемы. See the Known Issues forum to find workarounds to these issues and more.
Если режим разработчика не устанавливается правильно, мы рекомендуем отправить нам отзыв. If Developer Mode doesn’t install correctly, we encourage you to file a feedback request. В приложении Центр отзывов выберите Добавить новый отзыв, затем выберите категорию Платформа разработки и подкатегорию Режим разработчика. In the Feedback Hub app, select Add new feedback, and choose the Developer Platform category and the Developer Mode subcategory. Отправка отзыва поможет корпорации Майкрософт устранить проблему, с которой вы столкнулись. Submitting feedback will help Microsoft resolve the issue you encountered.
Сбой поиска пакета Failed to locate the package
«В Центре обновления Windows пакет режима разработчика не найден. «Developer Mode package couldn’t be located in Windows Update. Код ошибки 0x80004005. Подробнее». Error Code 0x80004005 Learn more»
Эта ошибка может возникать из-за проблемы сетевого подключения, неверной настройки корпоративных параметров или из-за отсутствия пакета. This error may occur due to a network connectivity problem, Enterprise settings, or the package may be missing.
Устранение проблемы: To fix this issue:
- Убедитесь, что компьютер подключен к Интернету. Ensure your computer is connected to the Internet.
- Если вы работаете на компьютере, подсоединенном к домену, обратитесь к своему сетевому администратору. If you are on a domain-joined computer, speak to your network administrator. Пакет режима разработчика, как и все компоненты по требованию, блокируется по умолчанию в службах WSUS. The Developer Mode package, like all Features on Demand, is blocked by default in WSUS. 2.1. 2.1. Чтобы разблокировать пакет режима разработчика в текущих и предыдущих выпусках, следует разрешить следующие обновления WSUS: 4016509, 3180030 и 3197985. In order to unblock the Developer Mode package in the current and previous releases, the following KBs should be allowed in WSUS: 4016509, 3180030, 3197985
- Проверьте наличие обновлений Windows в разделе «Параметры» > «Обновления и безопасность» > «Обновления Windows». Check for Windows updates in the Settings > Updates and Security > Windows Updates.
- Убедитесь, что пакет режима разработчика для Windows находится в разделе «Параметры» > «Система» > «Приложения и возможности» > «Управление дополнительными возможностями» > «Добавить возможность». Verify that the Windows Developer Mode package is present in Settings > System > Apps & Features > Manage optional features > Add a feature. Если его там нет, Windows не удастся найти правильный пакет для вашего компьютера. If it is missing, Windows cannot find the correct package for your computer.
После выполнения любого из описанных шагов отключите, а затем повторно включите режим разработчика, чтобы проверить его исправность. After doing any of the above steps, disable and then re-enable Developer Mode to verify the fix.
Сбой установки пакета Failed to install the package
«Не удалось установить пакет режима разработчика. «Developer Mode package failed to install. Код ошибки 0x80004005. Подробнее». Error code 0x80004005 Learn more»
Эта ошибка может возникать из-за наличия несовместимостей между вашей сборкой Windows и пакетом режима разработчика This error may occur due to incompatibilities between your build of Windows and the Developer Mode package.
Устранение проблемы: To fix this issue:
- Проверьте наличие обновлений Windows в разделе «Параметры» > «Обновления и безопасность» > «Обновления Windows». Check for Windows updates in the Settings > Updates and Security > Windows Updates.
- Перезагрузите компьютер, чтобы убедиться, что все обновления были применены. Reboot your computer to ensure all updates are applied.
Использование групповых политик или разделов реестра для подготовки устройства Use group policies or registry keys to enable a device
Большинство разработчиков будут использовать приложение «Параметры», чтобы включить в устройстве возможность отладки. For most developers, you want to use the settings app to enable your device for debugging. В некоторых сценариях, таких как автоматизированные тесты, можно использовать другие способы подготовки компьютера с Windows 10 для разработки. In certain scenarios, such as automated tests, you can use other ways to enable your Windows 10 desktop device for development. Следует помнить, что в ходе этих действий не выполняется включение сервера SSH и не предоставляется разрешение устройству на удаленное развертывание на нем или проведение отладки. Note that these steps will not enable the SSH server or allow the device to be targeted for remote deployment and debugging.
С помощью файла gpedit.msc можно включить режим разработчика на устройстве, используя групповые политики (кроме случая выпуска Windows 10 Домашняя). You can use gpedit.msc to set the group policies to enable your device, unless you have Windows 10 Home. Если у вас Windows 10 Домашняя, то, чтобы напрямую настроить разделы реестра для включения режима разработчика на устройстве, необходимо использовать программу regedit или команды PowerShell. If you do have Windows 10 Home, you need to use regedit or PowerShell commands to set the registry keys directly to enable your device.
Включение режима разработчика на устройстве с помощью команды gpedit Use gpedit to enable your device
Выполните команду Gpedit.msc. Run Gpedit.msc.
Последовательно выберите элементы Политика локального компьютера > Конфигурация компьютера > Административные шаблоны > Компоненты Windows > Развертывание пакета приложений Go to Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > App Package Deployment
Чтобы разрешить загрузку неопубликованных приложений, измените политики, чтобы включить параметр: To enable sideloading, edit the policies to enable:
- Разрешить установку всех доверенных приложений. Allow all trusted apps to install
Чтобы включить режим разработчика, измените политики, чтобы включить следующие параметры: To enable developer mode, edit the policies to enable both:
- Разрешить установку всех доверенных приложений. Allow all trusted apps to install
- Разрешить разработку приложений UWP и их установку из интегрированной среды разработки (IDE) . Allows development of UWP apps and installing them from an integrated development environment (IDE)
Перезагрузите компьютер. Reboot your machine.
Используйте команду regedit, чтобы включить режим разработчика на устройстве. Use regedit to enable your device
Выполните команду regedit. Run regedit.
Чтобы разрешить загрузку неопубликованных приложений, присвойте этому параметру типа DWORD значение 1: To enable sideloading, set the value of this DWORD to 1:
Чтобы включить режим разработчика, присвойте этому параметру типа DWORD значение 1: To enable developer mode, set the values of this DWORD to 1:
Включение режима разработчика на устройстве с помощью PowerShell Use PowerShell to enable your device
Запустите PowerShell с правами администратора. Run PowerShell with administrator privileges.
Чтобы разрешить загрузку неопубликованных приложений, выполните следующую команду: To enable sideloading, run this command:
Чтобы включить режим разработчика, выполните следующую команду: To enable developer mode, run this command:
Обновление устройства с Windows 8.1 до Windows 10 Upgrade your device from Windows 8.1 to Windows 10
Если вы хотите создавать приложения или загружать неопубликованные приложения на устройство с Windows 8.1, необходимо установить лицензию разработчика. When you create or sideload apps on your Windows 8.1 device, you have to install a developer license. При обновлении устройства с Windows 8.1 до Windows 10 эта информация сохранится. If you upgrade your device from Windows 8.1 to Windows 10, this information remains. Чтобы удалить эту информацию с устройства, обновленного до Windows 10, выполните указанную ниже команду. Run the following command to remove this information from your upgraded Windows 10 device. Это действие необязательно, если вы обновляете Windows 8.1 напрямую до Windows 10 версии 1511 или более поздней. This step is not required if you upgrade directly from Windows 8.1 to Windows 10, Version 1511 or later.
Отмена регистрации лицензии разработчика To unregister a developer license
- Запустите PowerShell с правами администратора. Run PowerShell with administrator privileges.
- Выполните следующую команду: unregister-windowsdeveloperlicense . Run this command: unregister-windowsdeveloperlicense .
После этого необходимо включить на устройстве режим разработчика, как описано в данной статье, чтобы можно было продолжить разработку на этом устройстве. After this you need to enable your device for development as described in this topic so that you can continue to develop on this device. Если не сделать этого, может возникнуть ошибка при отладке вашего приложения или при создании пакета для него. If you don’t do that, you might get an error when you debug your app, or you try to create a package for it. Ниже указан пример такой ошибки. Here is an example of this error:
Ошибка: DEP0700: не удалось зарегистрировать приложение. Error : DEP0700 : Registration of the app failed.