C# 获取视频采集卡信息并显示到 WinForm 中:DirectShow 示例
需要使用第三方库来获取视频采集卡信息,常用的有 DirectShow 和 FFmpeg。以下是使用 DirectShow 获取视频采集卡信息并显示到 WinForm 中的示例代码:
- 添加 DirectShow 库的引用
在 Visual Studio 中打开项目,右键单击项目,选择“添加引用”,在“COM”选项卡中选择“DirectShowLib”,点击“确定”按钮。
- 编写代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DirectShowLib;
namespace VideoCaptureCardInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 获取视频采集设备列表
List<string> deviceList = GetVideoCaptureDeviceList();
// 将设备列表显示到 ListBox 中
foreach (string deviceName in deviceList)
{
listBox1.Items.Add(deviceName);
}
}
private List<string> GetVideoCaptureDeviceList()
{
List<string> deviceList = new List<string>();
// 获取视频采集设备枚举器
IEnumMoniker enumMoniker = null;
Guid videoCaptureCategory = FilterCategory.VideoInputDevice;
int hr = 0;
hr = DsDevice.GetDevicesOfCat(videoCaptureCategory, out enumMoniker);
if (hr != 0)
{
throw new Exception("Failed to get video capture devices");
}
// 枚举每个视频采集设备
IMoniker[] monikerArray = new IMoniker[1];
while (enumMoniker.Next(1, monikerArray, IntPtr.Zero) == 0)
{
// 获取设备名称
IPropertyBag propertyBag = null;
hr = monikerArray[0].BindToStorage(null, null, typeof(IPropertyBag).GUID, out object obj);
if (hr != 0)
{
continue;
}
propertyBag = (IPropertyBag)obj;
object deviceNameObject = null;
hr = propertyBag.Read('FriendlyName', out deviceNameObject, null);
if (hr != 0)
{
continue;
}
string deviceName = (string)deviceNameObject;
deviceList.Add(deviceName);
}
return deviceList;
}
}
}
- 运行程序
启动程序后,会获取视频采集设备列表并显示到 ListBox 中。
注意:如果程序无法获取到视频采集设备列表,可能是由于 DirectShow 库没有正确安装或者设备驱动程序没有正确安装。
原文地址: https://www.cveoy.top/t/topic/oaNG 著作权归作者所有。请勿转载和采集!