martedì 4 agosto 2026

C# Windows Forms: ottenere le informazioni della webcam con WMI

In questo esempio, realizzato in linguaggio C# per un'applicazione Windows Forms, vedremo come recuperare alcune informazioni relative alla webcam installata sul computer.

Per ottenere questi dati utilizzeremo Windows Management Instrumentation (WMI) tramite la classe ManagementObjectSearcher, che esegue una query sulla classe Win32_PnPEntity. Gli oggetti restituiti, rappresentati dalla classe ManagementObject, consentono di accedere alle proprietà del dispositivo, come nome, produttore, identificativo del dispositivo e stato.

Inoltre, dal valore della proprietà PNPDeviceID estrarremo, mediante un'espressione regolare, il Vendor ID (VID) e il Product ID (PID) della webcam.

Di seguito è riportato il frammento di codice:


C# 

private void GetInfoWebCam()

 {

     try

     {

 

 

         var searcher = new ManagementObjectSearcher(

                         @"SELECT * FROM Win32_PnPEntity WHERE PNPClass='Camera'");

 

         foreach (ManagementObject mnoDevice in searcher.Get())

         {

             TxtNome.Text = mnoDevice["Name"].ToString();

             TxtProduttoreWebCam.Text = mnoDevice["Manufacturer"].ToString();

             TxtDeviceID.Text = mnoDevice["DeviceID"].ToString();

             TxtPNPID.Text = mnoDevice["PNPDeviceID"].ToString();

             TxtStato.Text = mnoDevice["Status"].ToString();

 

             string pnpId = mnoDevice["PNPDeviceID"]?.ToString() ?? "";

 

             var match = System.Text.RegularExpressions.Regex.Match(

                 pnpId,

                 @"VID_([0-9A-F]{4}).*PID_([0-9A-F]{4})");

 

             if (match.Success)

             {

                 TxtVendorID.Text = match.Groups[1].Value;

                 TxtProductID.Text = match.Groups[2].Value;

             }

         }

     }

     catch (ManagementException exMe)

     {

 

         Utility.MessaggioErrore("Errore: " + exMe.Message);

     }

 

     catch (Exception ex)

     {

         Utility.MessaggioErrore("Errore: " + ex.Message);

     }

 

 }

 


Nessun commento: