### Complete Screen Recording Workflow in C# Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt This snippet demonstrates the entire screen recording process, from initialization and capture selection to encoding and saving the final video file. It requires the CaptureEncoder, Windows.Graphics.Capture, and Windows.Media.MediaProperties namespaces. ```csharp using CaptureEncoder; using Windows.Graphics.Capture; using Windows.Graphics.DirectX.Direct3D11; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.Storage.Pickers; using Windows.System; public class ScreenRecorder { private IDirect3DDevice _device; private Encoder _encoder; public async Task InitializeAsync() { // Verify support if (!GraphicsCaptureSession.IsSupported()) { throw new NotSupportedException("Screen capture not supported"); } // Create Direct3D device _device = Direct3D11Helpers.CreateDevice(); } public async Task RecordAsync() { // Let user pick capture target var picker = new GraphicsCapturePicker(); var item = await picker.PickSingleItemAsync(); if (item == null) return; // Configure encoding settings var quality = VideoEncodingQuality.HD1080p; var profile = MediaEncodingProfile.CreateMp4(quality); uint width = (uint)item.Size.Width; uint height = (uint)item.Size.Height; width = width % 2 == 0 ? width : width + 1; height = height % 2 == 0 ? height : height + 1; uint bitrate = profile.Video.Bitrate; uint frameRate = 60; // Create temp file for recording var tempFolder = ApplicationData.Current.TemporaryFolder; var tempFile = await tempFolder.CreateFileAsync( $ירת{DateTime.Now:yyyyMMdd-HHmmss}.mp4", CreationCollisionOption.GenerateUniqueName); try { using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite)) using (_encoder = new Encoder(_device, item)) { // Record until encoder is disposed await _encoder.EncodeAsync(stream, width, height, bitrate, frameRate); } // Let user choose final location var savePicker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.VideosLibrary, SuggestedFileName = "recording", DefaultFileExtension = ".mp4" }; savePicker.FileTypeChoices.Add("MP4 Video", new[] { ".mp4" }); var destFile = await savePicker.PickSaveFileAsync(); if (destFile != null) { await tempFile.MoveAndReplaceAsync(destFile); await Launcher.LaunchFileAsync(destFile); } else { await tempFile.DeleteAsync(); } } catch (Exception ex) { // Handle encoding errors (e.g., unsupported hardware configuration) // Common error: MF_E_TRANSFORM_TYPE_NOT_SET (0xC00D6D60) Console.WriteLine($"Recording failed: {ex.Message}"); await tempFile.DeleteAsync(); } } public void StopRecording() { // Disposing the encoder stops the recording _encoder?.Dispose(); } } // Usage var recorder = new ScreenRecorder(); await recorder.InitializeAsync(); await recorder.RecordAsync(); // Returns when recording completes ``` -------------------------------- ### Configure and Execute Video Encoding Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Initializes the encoder with specific parameters and writes the captured stream to an MP4 file. ```csharp using CaptureEncoder; using Windows.Graphics.Capture; using Windows.Graphics.DirectX.Direct3D11; using Windows.Storage; using Windows.Storage.Streams; // Setup encoding parameters uint width = 1920; uint height = 1080; uint bitrateInBps = 18000000; // 18 Mbps uint frameRate = 60; // Ensure dimensions are even (required by many encoders) width = width % 2 == 0 ? width : width + 1; height = height % 2 == 0 ? height : height + 1; // Create the encoder with a Direct3D device and capture item using (var encoder = new Encoder(device, captureItem)) { // Create or open a file for writing StorageFile file = await ApplicationData.Current.TemporaryFolder .CreateFileAsync("recording.mp4", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { // Start encoding - this blocks until recording stops await encoder.EncodeAsync(stream, width, height, bitrateInBps, frameRate); } } // Encoding complete - file is ready Console.WriteLine("Recording saved!"); ``` -------------------------------- ### Initialize Direct3D11 Device Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Creates a Direct3D11 device for capture and encoding, supporting both hardware acceleration and WARP software rendering. ```csharp using CaptureEncoder; using Windows.Graphics.DirectX.Direct3D11; // Create a hardware-accelerated Direct3D11 device IDirect3DDevice device = Direct3D11Helpers.CreateDevice(); // Alternative: Create a software (WARP) device for testing or fallback IDirect3DDevice softwareDevice = Direct3D11Helpers.CreateDevice(useWARP: true); // The device is used for capture frame processing and encoding // Keep the device alive for the duration of capture operations ``` -------------------------------- ### Select Capture Source Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Uses the system picker to allow users to select a specific window or screen for recording. ```csharp using Windows.Graphics.Capture; // Create and show the capture picker var picker = new GraphicsCapturePicker(); GraphicsCaptureItem item = await picker.PickSingleItemAsync(); if (item == null) { // User cancelled the picker Console.WriteLine("Capture selection was cancelled"); return; } // Access capture item properties Console.WriteLine($"Selected: {item.DisplayName}"); Console.WriteLine($"Size: {item.Size.Width} x {item.Size.Height}"); // The item can now be used with the Encoder class ``` -------------------------------- ### Access Frame Data with SurfaceWithInfo Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Retrieves the Direct3D surface and timestamp from a captured frame for media sample creation. ```csharp using CaptureEncoder; using Windows.Graphics.DirectX.Direct3D11; using Windows.Media.Core; // SurfaceWithInfo is returned by CaptureFrameWait.WaitForNewFrame() using (SurfaceWithInfo frameInfo = captureFrameWait.WaitForNewFrame()) { if (frameInfo != null) { // Access the Direct3D surface containing the captured frame IDirect3DSurface surface = frameInfo.Surface; // Get the system-relative timestamp for the frame TimeSpan timestamp = frameInfo.SystemRelativeTime; // Create a media sample from the surface for encoding MediaStreamSample sample = MediaStreamSample.CreateFromDirect3D11Surface( surface, timestamp ); // The sample can be used with MediaStreamSource for transcoding } } // Surface is automatically disposed when SurfaceWithInfo is disposed ``` -------------------------------- ### Verify Screen Capture Support Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Checks if the current device supports the Windows.Graphics.Capture API. Required for Windows 10 version 1803 and later. ```csharp using Windows.Graphics.Capture; using Windows.UI.Popups; // Check if screen capture is supported on this device if (!GraphicsCaptureSession.IsSupported()) { var dialog = new MessageDialog( "Screen capture is not supported on this device for this release of Windows!", "Screen capture unsupported"); await dialog.ShowAsync(); return; } // Proceed with capture setup if supported Console.WriteLine("Screen capture is available!"); ``` -------------------------------- ### Handling Encoding Errors in C# Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt This snippet shows how to catch and handle specific encoding errors, such as unsupported hardware configurations, by checking the HResult of the exception. It uses a MessageDialog to inform the user about the failure. ```csharp using CaptureEncoder; using Windows.UI.Popups; try { using (var encoder = new Encoder(device, captureItem)) { using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await encoder.EncodeAsync(stream, width, height, bitrate, frameRate); } } } catch (Exception ex) { string message = GetErrorMessage(ex.HResult); var dialog = new MessageDialog(message, "Recording failed"); await dialog.ShowAsync(); } string GetErrorMessage(int hresult) { switch ((uint)hresult) { // MF_E_TRANSFORM_TYPE_NOT_SET - unsupported encoder configuration case 0xC00D6D60: return "The combination of options you've chosen are not supported by your hardware."; default: return $"An error occurred: 0x{hresult:X8}"; } } ``` -------------------------------- ### Configure Capture Resolution Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Sets the encoder to use the capture item's native resolution while ensuring even dimensions for compatibility. ```csharp using CaptureEncoder; using Windows.Graphics.Capture; using Windows.Media.MediaProperties; // Get encoding profile for bitrate based on quality preset var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p); uint bitrate = profile.Video.Bitrate; // Use the capture item's actual size uint width = (uint)captureItem.Size.Width; uint height = (uint)captureItem.Size.Height; // Ensure even dimensions for encoder compatibility if (width % 2 != 0) width++; if (height % 2 != 0) height++; using (var encoder = new Encoder(device, captureItem)) { using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await encoder.EncodeAsync(stream, width, height, bitrate, frameRate: 30); } } ``` -------------------------------- ### Capture Frames with CaptureFrameWait Source: https://context7.com/microsoftdocs/simplerecorder/llms.txt Manages thread-safe frame retrieval for Direct3D11 operations. Requires explicit disposal of the CaptureFrameWait instance. ```csharp using CaptureEncoder; using Windows.Graphics; using Windows.Graphics.Capture; using Windows.Graphics.DirectX.Direct3D11; // Initialize the frame capture system var frameWait = new CaptureFrameWait( device, // IDirect3DDevice captureItem, // GraphicsCaptureItem captureItem.Size // Initial capture size ); try { // Wait for and retrieve a new frame using (SurfaceWithInfo frame = frameWait.WaitForNewFrame()) { if (frame == null) { // Capture was closed or an error occurred Console.WriteLine("Capture ended"); return; } // Access frame data IDirect3DSurface surface = frame.Surface; TimeSpan timestamp = frame.SystemRelativeTime; Console.WriteLine($"Frame captured at {timestamp.TotalMilliseconds}ms"); // Process the surface (e.g., create MediaStreamSample) } } finally { frameWait.Dispose(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.