I want to use MediaCapture in a Windows Forms or WPF application, but apparently it is available only in UWP apps. How can we use that in a WPF or a Windows Forms application? There are many questions regarding this but none clearly address this.
Yes, you can use MediaCapture api in a WinForms or a WPF application. To do so you need to setup your project to target the right windows versions:
I've shared the project settings and code sample for .NET 6 and .NET Framework 4.8. To learn more, you can take a look at Call Windows Runtime APIs in desktop apps
Download or clone example
Create a WinForms application (.NET 6)
Edit the properties of the Project, and set the Target OS to 10.0.17763.0
or above. You can also modify the project file like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows10.0.17763.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
Drop a Button (button1) and a PictureBox (pictureBox1) on the form.
Handle the button click event, and add the following code to capture your picture using camera and convert it to a bitmap and show in the picture box:
private async void button1_Click(object sender, EventArgs e)
{
var mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();
mediaCapture.Failed += (obj, args) => MessageBox.Show(args.Message);
var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(
ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));
var capturedPhoto = await lowLagCapture.CaptureAsync();
var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;
await lowLagCapture.FinishAsync();
using (var stream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(
BitmapEncoder.PngEncoderId, stream);
encoder.SetSoftwareBitmap(softwareBitmap);
await encoder.FlushAsync();
pictureBox1.Image = new Bitmap(stream.AsStream());
}
}
With the following using statements:
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage.Streams;
using System.IO;
Set the PictureBox.SizeMode to Zoom.
Run the application, click on the button and see the picture in PictureBox.
The code of the example is like what I shared in the .NET 6 example, the only difference is in preparing the project and adding references. (I've shared the step for another answer as well.)
Microsoft.Windows.SDK.Contracts
package. In the right pane of the NuGet Package Manager window select the desired version of the package based on the version of Windows 10 you want to target and click install.More information and examples:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With