Demo程序
现在使用以上的实现过程就可以接收到设备通知了,下面的代码用于测试USB设备的插入和移除通知。
type TNotifier=class procedure OnUpdate(enumQueryUpdateAction: QueryUpdateAction; fdqcQueryContext: FDQUERYCONTEXT; pIFunctionInstance: IFunctionInstance); end; procedure NotificationDemo; Const Timeout = 20000; var hr : HResult; pIFunctionDiscoveryNotification : TFunctionDiscoveryNotificationSync; LNotifier : TNotifier; begin LNotifier:=TNotifier.Create; try pIFunctionDiscoveryNotification:=TFunctionDiscoveryNotificationSync.Create; try //set the callback pIFunctionDiscoveryNotification.OnUpdateEvent:=LNotifier.OnUpdate; Writeln(Format('Waiting for %d ms, to plug in a PnP device',[Timeout])); pIFunctionDiscoveryNotification.WaitFor(Timeout, FCTN_CATEGORY_PNP, QUA_ADD); Writeln('Done'); finally pIFunctionDiscoveryNotification:=nil; end; pIFunctionDiscoveryNotification:=TFunctionDiscoveryNotificationSync.Create; try //set the callback pIFunctionDiscoveryNotification.OnUpdateEvent:=LNotifier.OnUpdate; Writeln(Format('Waiting for %d ms, to remove a PnP device',[Timeout])); pIFunctionDiscoveryNotification.WaitFor(Timeout, FCTN_CATEGORY_PNP, QUA_REMOVE); Writeln('Done'); finally pIFunctionDiscoveryNotification:=nil; end; finally LNotifier.Free; end; end; { TNotifier } procedure TNotifier.OnUpdate(enumQueryUpdateAction: QueryUpdateAction; fdqcQueryContext: FDQUERYCONTEXT; pIFunctionInstance: IFunctionInstance); var ppIPropertyStore : IPropertyStore; pv : TPropVariant; begin case enumQueryUpdateAction of QUA_ADD : Writeln(Format('Action : %s',['Add'])); QUA_REMOVE : Writeln(Format('Action : %s',['Remove'])); QUA_CHANGE : Writeln(Format('Action : %s',['Change'])); end; if Succeeded(pIFunctionInstance.OpenPropertyStore(STGM_READ, ppIPropertyStore)) then if Succeeded(ppIPropertyStore.GetValue(PKEY_Device_DeviceDesc, pv)) then Writeln(Format('Device Desc. %s',[pv.pwszVal])); if Succeeded(ppIPropertyStore.GetValue(PKEY_Device_Class, pv)) then Writeln(Format('Class %s',[pv.pwszVal])); if Succeeded(ppIPropertyStore.GetValue(PKEY_Device_Manufacturer, pv)) then Writeln(Format('Manufacturer %s',[pv.pwszVal])); end; begin try ReportMemoryLeaksOnShutdown:=True; if (Win32MajorVersion >= 6) then // available on Vista (or later) begin if Succeeded(CoInitializeEx(nil, COINIT_MULTITHREADED)) then try NotificationDemo; finally CoUninitialize; end; end else Writeln('Windows version not compatible'); except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; end.
1 2
转载需保留链接来源:软件玩家 » Delphi XE3探索:Winapi.Functiondiscovery (三)