So I've been struggling with this problem for about a week now, and I finally figured it out today. I want to post my solution to the problem in hopes that it helps anyone who stumbles across this.
As the question asks, it's for a WPF .NET 5.0 project. It's pretty short, but there are a few things to note:
In your .csproj file, your TargetFramework
should be set to 10.0.17763.0 or higher (anything higher than 8.0). This will look like <TargetFramework>net5.0-windows10.0.20348.0</TargetFramework>
, which in my case is the latest framework available. If you don't have this, the Windows.Graphics.Capture
and WinRT.Interop
namespaces will not be available to you. These namespaces have the classes we need.
It's really only a slight fix from the answer @DaisyTian-1203 gave, but you don't need to fumble around with the Composition.WindowsRuntimeHelpers.dll
. Hope this helps someone out there!
Code in full:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using Windows.Graphics.Capture;
using WinRT.Interop;
namespace MyProject
{
public partial class MainWindow : Window
{
IntPtr Hwnd { get; set; }
public MainWindow()
{
InitializeComponent();
Loaded += OnLoad;
}
async void OnLoad(object sender, RoutedEventArgs e)
{
Trace.WriteLine("Application Loaded");
await StartPickerCaptureAsync();
}
async Task StartPickerCaptureAsync()
{
if (!GraphicsCaptureSession.IsSupported())
{
Trace.WriteLine("No Capture Support");
}
var interopWindow = new WindowInteropHelper(this);
Hwnd = interopWindow.Handle;
var picker = new GraphicsCapturePicker();
InitializeWithWindow.Initialize(picker, Hwnd);
var item = await picker.PickSingleItemAsync();
}
}
}