- 1 year ago
Enumerate Webcam Devices in Local System
To enumerate webcam devices in the local system using C++, you can utilize the Windows API functions and structures. Here's an example code snippet that demonstrates how to achieve this:
cpp#include <Windows.h>
#include <dshow.h>
#include <iostream>
int main() {
CoInitialize(nullptr);
// Create the System Device Enumerator
ICreateDevEnum* pDevEnum = nullptr;
CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum, reinterpret_cast<void**>(&pDevEnum));
// Create an enumerator for video input devices
IEnumMoniker* pEnum = nullptr;
pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0);
// Enumerate the devices
if (pEnum != nullptr) {
IMoniker* pMoniker = nullptr;
ULONG cFetched;
int deviceCount = 0;
while (pEnum->Next(1, &pMoniker, &cFetched) == S_OK) {
// Get the friendly name of the device
IPropertyBag* pPropBag;
pMoniker->BindToStorage(nullptr, nullptr, IID_IPropertyBag,
reinterpret_cast<void**>(&pPropBag));
VARIANT varName;
VariantInit(&varName);
pPropBag->Read(L"Description", &varName, nullptr);
// Print the device name
std::wcout << "Device " << ++deviceCount << ": "
<< varName.bstrVal << std::endl;
VariantClear(&varName);
pPropBag->Release();
pMoniker->Release();
}
pEnum->Release();
}
pDevEnum->Release();
CoUninitialize();
return 0;
}
This code utilizes the DirectShow API (dshow.h
) to enumerate the webcam devices on the local system. It creates a System Device Enumerator (ICreateDevEnum
) and then creates an enumerator specifically for video input devices (CLSID_VideoInputDeviceCategory
). It iterates through the devices, retrieves their friendly names using IPropertyBag
, and prints the names to the console.
Ensure that you link against the strmiids.lib
library and include the necessary headers (Windows.h
and dshow.h
) for successful compilation.
Note that DirectShow is a legacy API, and newer frameworks such as Media Foundation and Windows Imaging Component (WIC) are recommended for media-related tasks in modern Windows applications.