我想在Windows Forms或WPF应用程序中使用MediaCapture,但显然它仅在UWP应用程序中可用。我们如何在WPF或Windows Forms应用程序中使用它?有很多关于这个问题的问题,但没有一个清晰地解决了这个问题。
是的,您可以在WinForms或WPF应用程序中使用MediaCapture API。为此,您需要设置项目以针对正确的Windows版本:
我已经分享了.NET 6和.NET Framework 4.8的项目设置和代码示例。要了解更多信息,您可以查看在桌面应用程序中调用Windows Runtime API。
下载或克隆示例
创建一个 WinForms 应用程序(.NET 6)
编辑项目属性,将目标操作系统设置为 10.0.17763.0
或更高版本。您也可以像这样修改项目文件:
<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>
在窗体上放置一个按钮(button1)和一个图片框(pictureBox1)。
处理按钮单击事件,并添加以下代码以使用相机捕获您的照片并将其转换为位图并显示在图片框中:
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());
}
}
使用以下 using 语句:
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage.Streams;
using System.IO;
将 PictureBox.SizeMode 设置为 Zoom。
运行应用程序,单击按钮并在 PictureBox 中查看图片。
示例代码与我在.NET 6示例中分享的相同,唯一的区别在于准备项目和添加引用。(我还分享了另一个答案的步骤。)
Microsoft.Windows.SDK.Contracts
软件包。在NuGet软件包管理器窗口的右侧窗格中,根据您想要定位的Windows 10版本选择所需版本的软件包,然后单击安装。更多信息和示例: