Powershell:使用Hidlibrary的AsyncCallback事件 [英] Powershell: AsyncCallback Events using Hidlibrary
问题描述
我需要一些在Powershell中实现异步事件的帮助.
I need some help implementing asynchronous events in Powershell.
作为一个更大的HID项目的测试平台,我想使用Powershell从我从亚马逊起飞的USB应急按钮读取数据.完美的解决方案是将数据回调实现为一个事件,然后可以使用Register-ObjectEvent注册该事件.
As a testbed for a larger HID project I want to use Powershell to read the data from a usb panic button that I got off amazon. The perfect solution would implement the data callback as an event that could then be registered using Register-ObjectEvent.
我当前的方法是使用 Hidlibrary 库.我在调用Read()或ReadReport()方法时遇到困难.它们似乎不是典型的异步回调,并且使用 New-ScriptBlockCallback 的标准解决方案不起作用.
My current approach is to use the Hidlibrary library. I am having difficulty invoking both the Read() or ReadReport() methods. They do not appear to be typical asynccallbacks and the standard solution of using New-ScriptBlockCallback does not work.
到目前为止,我所能工作的并允许我拉起一个读柄.
What I have so far that works and allows me to pull a readhandle.
Add-Type -Path .\Projects\UsbPanicButton\HidLibrary.dll
$device = [HidLibrary.HidDevices]::GetDevice('\\?\hid#vid_1130&pid_0202&mi_00#7&29add023&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}')
$device.OpenDevice()
这不起作用. (找不到超载)
This does not work. (Cannot find an overload)
$device.ReadReport((New-ScriptBlockCallback {Write-host "HI"}))
如何将ReadReport方法转换为可以注册的事件?
How can I convert the ReadReport method into an event that can be registered?
推荐答案
ReadReport方法签名:
The ReadReport method signature:
public delegate void ReadReportCallback(HidReport report);
不适合New-ScriptBlockCallback.它与采用AsyncCallback参数的方法一起使用. IF 您知道可以在使用ReadReport方法调用期间在创建线程上调用回调:
Isn't a fit for New-ScriptBlockCallback. It works with methods taking an AsyncCallback parameter. IF you know the callback is called on the creating thread during the ReadReport method call you can use:
$device.ReadReport({param($hidReport) $hidReport.ReadStatus })
如果在其他线程上调用它,请尝试使用New-ScriptBlockCallback函数的此修改版本:
If it is called back on a different thread, try this modified version of the New-ScriptBlockCallback function:
function New-ScriptBlockCallback {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[scriptblock]$Callback
)
if (-not ("CallbackEventBridge" -as [type])) {
Add-Type @"
using System;
using HidLibrary;
public sealed class CallbackEventBridge
{
public event HidDevice.ReadReportCallback CallbackComplete = delegate { };
private CallbackEventBridge() {}
private void CallbackInternal(HidReport report)
{
CallbackComplete(report);
}
public HidDevice.ReadReportCallback Callback
{
get { return new HidDevice.ReadReportCallback(CallbackInternal); }
}
public static CallbackEventBridge Create()
{
return new CallbackEventBridge();
}
}
"@
}
$bridge = [callbackeventbridge]::create()
Register-ObjectEvent -input $bridge -EventName callbackcomplete -action $callback -messagedata $args > $null
$bridge.callback
}
这篇关于Powershell:使用Hidlibrary的AsyncCallback事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!