- Capture and apply Windows, system, and recovery partitions
- Capture the customized partitions
- Step 1: Determine which partitions to capture
- Step 2: Prepare to capture partitions
- Step 3: Capture images for each customized partition.
- Step 4: Save images to the network or another safe location.
- Apply the images
- Step 1: Prepare to apply partitions
- Step 2: Apply the partitions
- Step 3: Verify that it worked
- Снимок экрана Screen capture
- Добавление возможности захвата экрана Add the screen capture capability
- Запуск системного пользовательского интерфейса для создания снимка экрана Launch the system UI to start screen capture
- Создание пула кадров захвата и сеанса захвата Create a capture frame pool and capture session
- Получение кадров захвата Acquire capture frames
- Кадры захвата процесса Process capture frames
- Сделать снимок экрана Take a screenshot
- Реагирование на изменение размера элемента или потерю устройства React to capture item resizing or device lost
- Сборка Putting it all together
Capture and apply Windows, system, and recovery partitions
When you’re deploying Windows using the WIM format, and using customized partitions, a customized system partition or an additional utility partition, learn how to capture the right partitions to apply to new PCs.
If you don’t need custom partitions, you usually can just capture the Windows partition, and then use files from that image to set up the rest of the partitions on the drive. See Capture and Apply Windows using a single WIM file.
If you’re capturing using the FFU format, you’ll be fine — FFU captures all of the partitions on the drive.
Capture the customized partitions
Step 1: Determine which partitions to capture
This table shows the types of partitions that you must capture and those that are managed automatically.
If you’re deploying both UEFI and BIOS systems, you can reuse your primary and logical partitions across UEFI-based and BIOS-based devices, but not the other partition types.
Partition type | Should you capture this partition? | Can you reuse the same WIM on UEFI and BIOS firmware? |
---|---|---|
System partition (EFI System Partition or BIOS system partition) | Optional. If only a simple set of partition files is required, you don’t have to capture this partition. | No |
Microsoft Reserved partition (MSR) | No | No |
Primary partitions (Windows partitions, data / utility partitions that you’ve added) | Yes | Yes |
Recovery partition | Optional. If you haven’t customized this partition, you don’t have to capture it. | No |
Extended partition | No | No |
Logical partitions (Windows partitions, data / utility partitions that you’ve added) | Yes | Yes |
Step 2: Prepare to capture partitions
If you’ve booted the Windows image, generalize it so that it can be deployed to other devices. For more information, see Sysprep (Generalize) a Windows installation.
Start your reference device by using WindowsВ PE.
At the WindowsВ PE command prompt, type diskpart to open the DiskPart tool.
Check to see if the partitions that you want to capture have drive letters assigned.
If any of the partitions you want to capture don’t already have a drive letter assigned, continue:
List the disks in your PC:
Select the primary hard disk:
View the partitions:
Select a partition that needs a drive letter:
Assign a letter to the partition with the assign letter command. For example,
Type exit to return to the WindowsВ PE command prompt.
For more information, see the DiskPart Help from the command line, or Diskpart Command line syntax.
Step 3: Capture images for each customized partition.
At the WindowsВ PE command prompt, capture each customized partition, for example:
For more information about using the DISM tool to capture an image, see DISM Image Management Command-Line Options.
Step 4: Save images to the network or another safe location.
Connect an external drive, or connect to a safe network location, for example:
If prompted, provide your network credentials.
Copy the partitions to your network share. For example,
Apply the images
Step 1: Prepare to apply partitions
Start your destination device by using WindowsВ PE.
Connect an external drive, or connect to a safe network location, for example:
If prompted, provide your network credentials.
Wipe the hard drive and create new partitions.
To apply to multiple devices, save the Diskpart commands into a script and run them on each new device. For examples, see Configure UEFI/GPT-Based Hard Drive Partitions or Configure BIOS/MBR-Based Hard Drive Partitions. Example:
Where D: is a USB flash drive or other file storage location.
In these DiskPart examples, the partitions are assigned the letters: System=S, Windows=W, and Recovery=R.
Change the Windows drive letter to a letter that’s near the end of the alphabet, such as W, to avoid drive letter conflicts. Do not use X, because this drive letter is reserved for Windows PE. After the device reboots, the Windows partition is assigned the letter C, and the other partitions don’t receive drive letters.
If you reboot, WindowsВ PE reassigns disk letters alphabetically, starting with the letter C, without regard to the configuration in Windows Setup. This configuration can change based on the presence of different drives, such as USB flash drives.
Optional: speed up the image capture by setting the power scheme to High performance:
Step 2: Apply the partitions
Windows and data partitions: Apply the image(s), example:
where W: is the Windows partition.
System partition: You can either:
Configure the system partition by using the BCDBoot tool. This tool copies and configures system partition files by using files from the Windows partition. For example:
Apply a custom image
Where S: is the system partition
Recovery partition:
a. You can either:
Copy the Windows Recovery Environment (RE) tools into the recovery tools partition.
Where R: is the recovery partition
Apply a custom image
b. Register the location of the recovery tools, and hide the recovery partition using Diskpart. You can use our sample script or perform the steps manually:
Diskpart steps for UEFI:
Diskpart steps for BIOS:
Step 3: Verify that it worked
Reboot the device ( exit ). Windows should boot.
If the device doesn’t boot, (for example, if you receive the error message: Bootmgr not found. Press CTRL+ALT+DEL) check the steps for setting up the system partition:
- See BCDBoot command-line options for more info about copying boot files to the system partition.
- Use the DiskPart tool to check to make sure that the system partition is set to Active.
Complete the out of box experience (OOBE) as a new user, and check the recovery partition:
Check that in File Explorer that the Recovery partition is not visible.
View the partitions exist, either by right-clicking Start and selecting Disk Management, or by using diskpart (Open a command prompt as an administrator > diskpart > select disk 0 > list partition > exit ).
Снимок экрана Screen capture
Начиная с Windows 10 версии 1803 пространство имен Windows.Graphics.Capture предоставляет API-интерфейсы для извлечения кадров из окна отображения или приложения, создания видеопотоков или снимков в рамках формирования интерактивного интерфейса для совместной работы. Starting in Windows 10, version 1803, the Windows.Graphics.Capture namespace provides APIs to acquire frames from a display or application window, to create video streams or snapshots to build collaborative and interactive experiences.
Снимок экрана позволяет разработчикам вызывать безопасный системный интерфейс, чтобы конечные пользователи могли выбрать экран или окно приложения для захвата, после чего систему рисует желтую границу уведомления вокруг активного элемента. With screen capture, developers invoke secure system UI for end users to pick the display or application window to be captured, and a yellow notification border is drawn by the system around the actively captured item. В случае синхронных сеансов захвата желтая граница рисуется вокруг каждого элемента, снимок которого создается. In the case of multiple simultaneous capture sessions, a yellow border is drawn around each item being captured.
API-интерфейсы захвата экрана поддерживаются только на настольных и впечатляющих гарнитурах Windows Mixed Reality. The screen capture APIs are only supported on desktop and Windows Mixed Reality immersive headsets.
В этой статье описывается запись одного изображения окна просмотра или приложения. This article describes capturing a single image of the display or application window. Сведения о кодировании кадров, записанных с экрана в видеофайл, см. в разделе снимок экрана в видео . For information on encoding frames captured from the screen to a video file, see Screen capture to video
Добавление возможности захвата экрана Add the screen capture capability
Для API-интерфейсов, обнаруженных в пространстве имен Windows. Graphics. Capture , требуется объявление общей возможности в манифесте приложения: The APIs found in the Windows.Graphics.Capture namespace require a general capability to be declared in your application’s manifest:
- Откройте Package. appxmanifest в Обозреватель решений. Open Package.appxmanifest in the Solution Explorer.
- Перейдите на вкладку Возможности. Select the Capabilities tab.
- Проверьте видеозапись графических объектов. Check Graphics Capture.
Запуск системного пользовательского интерфейса для создания снимка экрана Launch the system UI to start screen capture
Перед запуском системного пользовательского интерфейса можно проверить, может ли ваше приложение создавать снимки экрана. Before launching the system UI, you can check to see if your application is currently able to take screen captures. Существует несколько причин, из-за которых приложение не может использовать снимок экрана — например, устройство не соответствует требованиям к оборудованию или приложение ориентировано на блочный захват экрана. There are several reasons why your application might not be able to use screen capture, including if the device does not meet hardware requirements or if the application targeted for capture blocks screen capture. Используйте метод IsSupported класса GraphicsCaptureSession, чтобы определить, поддерживается ли снимок экрана UWP: Use the IsSupported method in the GraphicsCaptureSession class to determine if UWP screen capture is supported:
Когда вы убедитесь, что снимок экрана поддерживается, используйте класс GraphicsCapturePicker для вызова интерфейса системного средства выбора. Once you’ve verified that screen capture is supported, use the GraphicsCapturePicker class to invoke the system picker UI. Конечный пользователь применяет этот интерфейс для выбора экрана или окна приложения, из которого требуется делать снимки экрана. The end user uses this UI to select the display or application window of which to take screen captures. Средство выбора вернет элемент GraphicsCaptureItem, который будет использоваться для создания GraphicsCaptureSession: The picker will return a GraphicsCaptureItem that will be used to create a GraphicsCaptureSession:
Поскольку это код пользовательского интерфейса, его необходимо вызывать в потоке пользовательского интерфейса. Because this is UI code, it needs to be called on the UI thread. Если вы вызываете его из кода программной части для страницы приложения (например, MainPage.XAML.CS), это выполняется автоматически, но в противном случае можно принудительно запустить его в ПОТОКЕ пользовательского интерфейса с помощью следующего кода: If you’re calling it from the code-behind for a page of your application (like MainPage.xaml.cs) this is done for you automatically, but if not, you can force it to run on the UI thread with the following code:
Создание пула кадров захвата и сеанса захвата Create a capture frame pool and capture session
С помощью графикскаптуреитем вы создадите DIRECT3D11CAPTUREFRAMEPOOL с устройством D3D, поддерживаемым форматом пикселей (в формате DXGI _ _ B8G8R8A8 _ UNORM), числом нужных кадров (которое может быть любым целым числом) и размером кадра. Using the GraphicsCaptureItem, you will create a Direct3D11CaptureFramePool with your D3D device, supported pixel format (DXGI_FORMAT_B8G8R8A8_UNORM), number of desired frames (which can be any integer), and frame size. Свойство ContentSize класса GraphicsCaptureItem класс можно использовать в качестве размера кадра: The ContentSize property of the GraphicsCaptureItem class can be used as the size of your frame:
В системах с включенным цветом Windows HD формат пикселей содержимого может быть не всегда в _ формате DXGI _ B8G8R8A8 _ UNORM. On systems with Windows HD color enabled, the content pixel format might not necessarily be DXGI_FORMAT_B8G8R8A8_UNORM. Чтобы избежать пересечения пикселей (т. е. захваченного содержимого с нештатным наполнением) при записи HDR-содержимого, рассмотрите возможность использования _ формата DXGI _ R16G16B16A16 _ float для каждого компонента в конвейере записи, включая Direct3D11CaptureFramePool, целевое назначение, например канвасбитмап. To avoid pixel overclipping (i.e. the captured content looks washed out) when capturing HDR content, consider using DXGI_FORMAT_R16G16B16A16_FLOAT for every component in the capturing pipeline, including the Direct3D11CaptureFramePool, the target destination such as CanvasBitmap. Зависит от нужды, может потребоваться дополнительная обработка, например сохранение в формате HDR-содержимого или сопоставление тонов из HDR в SDR. Depends on the need, additional processing such as saving to HDR content format or HDR-to-SDR tone mapping might be required. В этой статье рассматривается запись содержимого SDR. This article will focus on SDR content capturing. Дополнительные сведения см. в статье Использование DirectX с высоким динамическим диапазоном отображения и расширенным цветом. For more information, please see Using DirectX with high dynamic range Displays and Advanced Color.
Затем получите экземпляр класса GraphicsCaptureSession для пула Direct3D11CaptureFramePool, передав GraphicsCaptureItem методу CreateCaptureSession: Next, get an instance of the GraphicsCaptureSession class for your Direct3D11CaptureFramePool by passing the GraphicsCaptureItem to the CreateCaptureSession method:
Если пользователь явно предоставил согласие на захват окна или экрана приложения в системном интерфейсе, GraphicsCaptureItem можно связать с несколькими объектами CaptureSession. Once the user has explicitly given consent to capturing an application window or display in the system UI, the GraphicsCaptureItem can be associated to multiple CaptureSession objects. Таким образом ваше приложение может записывать один и тот же элемент для различных процессов. This way your application can choose to capture the same item for various experiences.
Для одновременного захвата нескольких элементов приложение должно создать сеанса захвата для каждого записываемого элемента. Для этого требуется вызвать интерфейс средства выбора для каждого элемента. To capture multiple items at the same time, your application must create a capture session for each item to be captured, which requires invoking the picker UI for each item that is to be captured.
Получение кадров захвата Acquire capture frames
После создания пула кадров и сеанса захвата, вызовите метод StartCapture метод экземпляра GraphicsCaptureSession, чтобы система начала отправлять кадры захвата вашему приложению: With your frame pool and capture session created, call the StartCapture method on your GraphicsCaptureSession instance to notify the system to start sending capture frames to your app:
Для получения этих кадров захвата, которые являются объектами Direct3D11CaptureFrame, можно использовать событие Direct3D11CaptureFramePool.FrameArrived: To acquire these capture frames, which are Direct3D11CaptureFrame objects, you can use the Direct3D11CaptureFramePool.FrameArrived event:
Не рекомендуется использовать поток пользовательского интерфейса, если это возможно, для FrameArrived, так как это событие вызывается каждый раз, когда доступен новый кадр, что происходит довольно часто. It is recommended to avoid using the UI thread if possible for FrameArrived, as this event will be raised every time a new frame is available, which will be frequent. Если вы решили прослушивать FrameArrived в потоке пользовательского интерфейса, обратите внимание на действия, которые вы выполняете при каждом событии. If you do choose to listen to FrameArrived on the UI thread, be mindful of how much work you’re doing every time the event fires.
Кроме того, вы можете вручную извлекать кадры с помощью метода Direct3D11CaptureFramePool.TryGetNextFrame, пока не получите все нужные кадры. Alternatively, you can manually pull frames with the Direct3D11CaptureFramePool.TryGetNextFrame method until you get all of the frames that you need.
Объект Direct3D11CaptureFrame содержит свойства размер содержимого, Surface и SystemRelativeTime. The Direct3D11CaptureFrame object contains the properties ContentSize, Surface, and SystemRelativeTime. SystemRelativeTime — это время QPC (QueryPerformanceCounter), которое можно использовать для синхронизации с другими элементами мультимедиа. The SystemRelativeTime is QPC (QueryPerformanceCounter) time that can be used to synchronize other media elements.
Кадры захвата процесса Process capture frames
Каждый кадр Direct3D11CaptureFramePool извлекается при вызове TryGetNextFrame и возвращается в соответствии с временем жизни объекта Direct3D11CaptureFrame. Each frame from the Direct3D11CaptureFramePool is checked out when calling TryGetNextFrame, and checked back in according to the lifetime of the Direct3D11CaptureFrame object. Для собственных приложений освобождения объекта Direct3D11CaptureFrame достаточно для возврата кадра в пул. For native applications, releasing the Direct3D11CaptureFrame object is enough to check the frame back in to the frame pool. Для управляемых приложений рекомендуется использовать метод Direct3D11CaptureFrame.Dispose (Close на C++). For managed applications, it is recommended to use the Direct3D11CaptureFrame.Dispose (Close in C++) method. Direct3D11CaptureFrame реализует интерфейс IClosable, который проецируется как IDisposable для вызывающих объектов C#. Direct3D11CaptureFrame implements the IClosable interface, which is projected as IDisposable for C# callers.
Приложения не должны сохранять ссылки на объекты Direct3D11CaptureFrame и не должны сохранять ссылки на базовую поверхность Direct3D после возврата кадра. Applications should not save references to Direct3D11CaptureFrame objects, nor should they save references to the underlying Direct3D surface after the frame has been checked back in.
При обработке кадра приложениям рекомендуется получать блокировку ID3D11Multithread на устройстве, которое связано с объектом Direct3D11CaptureFramePool. While processing a frame, it is recommended that applications take the ID3D11Multithread lock on the same device that is associated with the Direct3D11CaptureFramePool object.
Размер базовой поверхности Direct3D всегда равен размеру, указанному при создании (или повторном создании) Direct3D11CaptureFramePool. The underlying Direct3D surface will always be the size specified when creating (or recreating) the Direct3D11CaptureFramePool. Если содержимое больше кадра, оно обрезается по размеру кадра. If content is larger than the frame, the contents are clipped to the size of the frame. Если содержимое меньше кадра, остальная часть кадра содержит неопределенные данные. If the content is smaller than the frame, then the rest of the frame contains undefined data. Приложениям рекомендуется копировать прямоугольник с помощью свойства ContentSize для этого кадра Direct3D11CaptureFrame, чтобы не отображать неопределенное содержимое. It is recommended that applications copy out a sub-rect using the ContentSize property for that Direct3D11CaptureFrame to avoid showing undefined content.
Сделать снимок экрана Take a screenshot
В нашем примере мы преобразуем каждый Direct3D11CaptureFrame в канвасбитмап, который является частью API Win2D. In our example, we convert each Direct3D11CaptureFrame into a CanvasBitmap, which is part of the Win2D APIs.
После получения канвасбитмап можно сохранить его как файл изображения. Once we have the CanvasBitmap, we can save it as an image file. В следующем примере мы сохраняем его как PNG-файл в папке сохраненные рисунки пользователя. In the following example, we save it as a PNG file in the user’s Saved Pictures folder.
Реагирование на изменение размера элемента или потерю устройства React to capture item resizing or device lost
Во время захвата приложениям может потребоваться изменить аспекты Direct3D11CaptureFramePool. During the capture process, applications may wish to change aspects of their Direct3D11CaptureFramePool. В том числе может понадобиться предоставить новое устройство Direct3D, изменить размер буферов кадров или даже изменить количество буферов в пуле. This includes providing a new Direct3D device, changing the size of the frame buffers, or even changing the number of buffers within the pool. В каждом из этих случаев рекомендуется использовать метод Recreate объекта Direct3D11CaptureFramePool. In each of these scenarios, the Recreate method on the Direct3D11CaptureFramePool object is the recommended tool.
При вызове Recreate удаляются все существующие кадры. When Recreate is called, all existing frames are discarded. Это необходимо для предотвращения передачи кадров, базовые поверхности Direct3D которых принадлежат устройству, которое больше недоступно приложению. This is to prevent handing out frames whose underlying Direct3D surfaces belong to a device that the application may no longer have access to. Поэтому может быть логичным обработать все ожидающие кадры перед вызовом Recreate. For this reason, it may be wise to process all pending frames before calling Recreate.
Сборка Putting it all together
В следующем фрагменте кода приведен полный пример реализации снимка экрана в приложении UWP. The following code snippet is an end-to-end example of how to implement screen capture in a UWP application. В этом примере у нас есть две кнопки в интерфейсной части: один вызывает Button_ClickAsync, а другой вызывает ScreenshotButton_ClickAsync. In this sample, we have two buttons in the front-end: one calls Button_ClickAsync, and the other calls ScreenshotButton_ClickAsync.
В этом фрагменте кода используется Win2D— библиотека для отрисовки двухмерной графики. This snippet uses Win2D, a library for 2D graphics rendering. Сведения о том, как настроить проект, см. в их документации. See their documentation for information about how to set it up for your project.