检测单击 TreeView 中的 +/- 按钮/将 C# 转换为 Powershell

Detect click on the +/- button in a TreeView / Conversion of C# to Powershell

我有一个带有 winform 和 treeview 的 powershell 脚本。

现在我需要区分用户是单击了 winforms treeview 节点name 还是 在节点前加上或减去.

如果找到此代码:

private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    var hitTest = treeView1.HitTest(e.Location);
    if (hitTest.Location == TreeViewHitTestLocations.PlusMinus)
    { 
        //expand collapse clicked
    }
}

在此answer。我试图将它翻译成 Powershell(见下文)并且它似乎有效......但是: 问题是,无论我点击哪里,结果总是“indent”,这是可能的 return 值之一 (TreeViewHitTestLocations-Enumeration) 但它不应该总是一样的,无论我点击哪里。

$hitlocation = $treeview1.HitTest($treeview1.Location)
Write-Debug "$($hitlocation.location)"

if ($hitlocation.Location -eq [System.Windows.Forms.TreeViewHitTestLocations]::PlusMinus){ 
   # do stuff
   write-host "yes!"
}

那么问题来了,是我翻译错了代码,还是其他问题?

在原始示例中,HitTest() 是针对传递的 EventArgs 对象携带的 Location 值执行的。在您的示例中,您对 $treeview1.Location 执行 HitTest(),我假设无论您单击何处都保持不变。

注册事件操作时,定义一个包含 2 个参数的参数块(对于您在 C# 示例中看到的 sendere 参数):

$treeview1.add_MouseDoubleClick({

    param($s,$e)

    # Now we can refer to $e like in the example
    $hitlocation = $treeview1.HitTest($e.Location)
    Write-Debug "$($hitlocation.Location)"

    if ($hitlocation.Location -eq [System.Windows.Forms.TreeViewHitTestLocations]::PlusMinus){ 
       # do stuff
       write-host "yes!"
    }
})