WPF 和 Powershell 的键盘快捷键

Keyboard shortcuts with WPF and Powershell

在下面的代码中:

Add-Type -AssemblyName PresentationFramework
$window = New-Object Windows.Window
$commonKeyEvents = {
    [System.Windows.Input.KeyEventArgs] $e = $args[1]
    if ($e.Key -eq 'ESC') { $this.close() }
    if ($e.Key -eq 'Ctrl+Q') { $this.close() }
}
$window.add_PreViewKeyDown($commonKeyEvents)
$window.ShowDialog() | Out-Null

'Ctrl+Q' 部分不起作用。我怎么能让这个工作?

你在这里:

Add-Type -AssemblyName PresentationFramework
$window = New-Object Windows.Window

$commonKeyEvents = {
    [System.Windows.Input.KeyEventArgs] $e = $args[1]

    if (($e.Key -eq "Q" -and $e.KeyboardDevice.Modifiers -eq "Ctrl") -or
        ($e.Key -eq "ESC")) {            
        $this.Close()
    }
}

$window.Add_PreViewKeyDown($commonKeyEvents)
$window.ShowDialog() | Out-Null

更简单:

Add-Type -AssemblyName PresentationFramework
$window = New-Object Windows.Window

$commonKeyEvents = {
    if (($_.Key -eq "Q" -and $_.KeyboardDevice.Modifiers -eq "Ctrl") -or
        ($_.Key -eq "ESC")) {            
        $this.Close()
    }
}

$window.Add_PreViewKeyDown($commonKeyEvents)
$window.ShowDialog() | Out-Null
Add-Type -AssemblyName PresentationFramework
$window = New-Object Windows.Window
$commonKeyEvents = {
    [System.Windows.Input.KeyEventArgs]$e = $args[1]
    if ($e.Key -eq 'Escape') { $this.close() }
    if ([System.Windows.Input.KeyBoard]::Modifiers -eq [System.Windows.Input.ModifierKeys]::Control -and $e.Key -eq 'Q') { $this.close() }
}
$window.add_KeyDown($commonKeyEvents)
$window.ShowDialog() | Out-Null