在与Chat GPT和Bing聊天进行了一晚的辩论后,我现在转向Stackoverflow的(希望)更聪明的人.我的问题是:我有用C#实现的低级钩子.我在PowerShell类中订阅事件,然后在图形用户界面中使用它.订阅事件并启动钩子工作得很好,但是,我不能从我的类或图形用户界面程序中停止钩子.现在我在想,只要我按下‘f4’,钩子就应该停止,但我一直收到‘无法在空值表达式上调用方法’的消息,我真的不明白为什么它会是空值的,或者我该如何解决它.下面是我的代码,我认为没有必要显示钩子或图形用户界面的实现,但请让我知道.
class InputRecorder {
[KeyboardHookExample.KeyboardHook] $kh
[Ikst.MouseHook.MouseHook] $mh
[System.Windows.Forms.ListView] $list
InputRecorder() {
$this.kh = New-Object KeyboardHookExample.KeyboardHook
$this.mh = New-Object Ikst.MouseHook.MouseHook
# Store the reference to the class instance
$self = $this
# Define the event handler for KeyDown
$self.kh.add_KeyDown({
param($sender, $e)
$vkCode = $sender.vkCode
Write-Host $vkCode
if ($vkCode -eq 115) {
$self.kh.Stop()
$self.mh.Stop()
}
$charCode = [Win32.NativeMethods]::MapVirtualKey($vkCode, 2)
$char = [char]$charCode
Write-Host $char
})
# Define the event handler for LeftButtonDown
$self.mh.add_LeftButtonDown({
param($sender, $e)
$mousePosition = $sender.pt
$y = $mousePosition.y
$x = $mousePosition.x
$item = New-Object System.Windows.Forms.ListViewItem
$item.ToolTipText = $global:dict["LeftClickCode"] -f $x, $y
$item.Text = $global:dict["LeftClickDescription"] -f $x, $y
$CMDList.Items.Add($item)
})
# Start the keyboard and mouse hooks
$self.kh.Start()
$self.mh.Start()
}
[System.Collections.Concurrent.ConcurrentBag[string]] getList() {
return $this.list
}
[void] StopHooks() {
$this.mh.Stop()
$this.kh.Stop()
}
}