简体   繁体   中英

Detect if a device (printer, scanner, mouse, etc…) isn't working

If a printer has a problem, Windows's Device manager shows a special icon next to the printer in question.

I'm using Delphi XE2 and I'd like to know how to programmatically detect such info for Windows XP or later, ie.

function DetectDriversProblems() : TStringList;
begin
    // Scan Computer or query Windows to know if a driver has issues and
    // return list of faulty hardware (if any)
end;

you can use the Win32_PnPEntity WMI class and ConfigManagerErrorCode property.

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;

  Procedure ListDevicesConfigError;
    const
      wbemFlagForwardOnly = $00000020;
    var
      FSWbemLocator : OLEVariant;
      FWMIService   : OLEVariant;
      FWbemObjectSet: OLEVariant;
      FWbemObject   : OLEVariant;
      oEnum         : IEnumvariant;
      iValue        : LongWord;
    begin;
      FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
      FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\cimv2', '', '');
      FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM  Win32_PnPEntity WHERE ConfigManagerErrorCode <> 0','WQL',wbemFlagForwardOnly);
      oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
      while oEnum.Next(1, FWbemObject, iValue) = 0 do
      begin
        Writeln(Format('Class GUID %s',[String(FWbemObject.ClassGUID)]));
        Writeln(Format('Description %s',[String(FWbemObject.Description)]));
        Writeln(Format('Device ID %s',[String(FWbemObject.DeviceID)]));
        Writeln(Format('Manufacturer %s',[String(FWbemObject.Manufacturer)]));
        Writeln(Format('Name %s',[String(FWbemObject.Name)]));
        Writeln(Format('PNP Device ID %s',[String(FWbemObject.PNPDeviceID)]));
        Writeln('');
        FWbemObject:=Unassigned;
      end;
    end;

begin
 try
    CoInitialize(nil);
    try
      ListDevicesConfigError;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode])); 
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;      
end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM