首先,OnEvent()不应声明为dynamic. 它已经virtual在IPortableDeviceEventCallback.
其次,您没有对 进行任何错误处理IPortableDeviceValues.GetStringValue(),也没有释放它返回的内存。它应该看起来更像这样:
function TPortableDeviceEventsCallback.OnEvent(const pEventParameters: IPortableDeviceValues): HResult;
var
Hr: HResult;
ObjName: PWideChar;
begin
Hr := pEventParameters.GetStringValue(WPD_EVENT_PARAMETER_OBJECT_NAME, ObjName);
case Hr of
S_OK: begin
try
Log('Object Name: ' + String(ObjName));
finally
CoTaskMemFree(ObjName);
end;
end;
DISP_E_TYPEMISMATCH: begin
Log('Object Name is not a string!');
end;
$80070490: // HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
begin
Log('Object Name is not found!');
end;
else
// some other error
Log('Error getting Object Name: $' + IntToHex(Hr, 8));
end;
Result := S_OK;
end;
第三,您不是查看WPD_EVENT_PARAMETER_EVENT_ID参数的值(这是唯一需要的参数)来了解您正在接收什么事件,以便了解它可以使用哪些参数。不同的事件有不同的参数值。
尝试枚举可用值以查看您在每个事件中实际收到的内容:
function TPortableDeviceEventsCallback.OnEvent(const pEventParameters: IPortableDeviceValues): HResult;
var
Hr: HResult;
Count, I: DWORD;
Key: PROPERTYKEY;
Value: PROPVARIANT;
begin
Log('Event received');
Hr := pEventParameters.GetCount(Count);
if FAILED(Hr) or (Count = 0) then Exit;
Log('Param count: ' + IntToStr(Count));
for I := 0 to Count-1 do
begin
Hr := pEventParameters.GetAt(I, Key, Value);
if FAILED(Hr) then
begin
Log('Cant get parameter at index ' + IntToStr(I));
Continue;
end;
try
Log('Param Key: ' + GuidToString(Key.fmtid) + ', Value type: $' + IntToHex(Value.vt, 4));
// log content of Value based on its particular data type as needed...
finally
PropVariantClear(Value);
end;
end;
Result := S_OK;
end;