MediaCapture API in WPF or Windows Forms
Asked Answered
D

1

4

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.

Duggan answered 29/12, 2022 at 4:3 Comment(0)
S
4

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:

  • For .NET 6, you can set the Target OS in properties to 10.0.17763.0 or above (or set the TargetFramrwork in project file to net6.0-windows10.0.17763.0)
  • For .NET 4.8, you can enable PackageReference for package manager, and install Microsoft.Windows.SDK.Contracts package. (10.0.17763.0 or above).

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

Capture image by MediaCapture - WinForms .NET 6

  1. Create a WinForms application (.NET 6)

  2. 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>
    
  3. Drop a Button (button1) and a PictureBox (pictureBox1) on the form.

  4. 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;
    
  5. Set the PictureBox.SizeMode to Zoom.

  6. Run the application, click on the button and see the picture in PictureBox.

Capture image by MediaCapture - WinForms .NET 4.8

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.)

  1. Go to Tools → Set the "Default package management format" to "PackageReference"
  2. Solution Explorer → Right click on your project → choose Manage NuGet Packages, and
  3. Find 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.
  4. Follow the previous example from step 3.

More information and examples:

Sextuplicate answered 29/12, 2022 at 10:13 Comment(8)
Thank you @Reza-aghaei for replying. Can we use this for older version of Windows 10 as well?Duggan
Looking into this doc and in the package versions., the lowest version that I see for .NET 4.x: '10.0.17134.xxxx: Choose this for Windows 10, version 1803.' and for .NET 6: 'net6.0-windows10.0.17763.0: If your app targets Windows 10, version 1809.'.Sextuplicate
Download the source or clone the repository and give it a try on your target Windows. The example is ready to run and it contains both .NET6 and .NET 4.8 projects.Sextuplicate
Thank you. This works great and fetches a frame from webcam. I was able to modify it a little and use in WPF project too. Can you explain how to show webcam video? in UWP app, it uses CaptureElement but its not available in WPFDuggan
I edited the question to include the Windows Forms in title, body and tags. Please do not remove as it makes the answer nonsense. The post answers your original question about How to use MediaCapture API in WinForms or WPF. If you have a more specific scenario, then please ask a new question.Sextuplicate
I agree. It was closed and it was suggested to add more details, so I had to. Will post separate question with more details. Thanks for your time.Duggan
@Duggan Could you please post your working code for WPF, maybe as another answer?Measureless
@Measureless I have added a WPF project sample in this fork github.com/dotriz/MediaCaptureApiExampleDuggan

© 2022 - 2024 — McMap. All rights reserved.