TNT
TNT

Reputation: 3620

Keyboard shortcuts with WPF and Powershell

In the following code:

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

the 'Ctrl+Q' part does not work. How could I make this work?

Upvotes: 3

Views: 730

Answers (2)

sodawillow
sodawillow

Reputation: 13176

Here you are:

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

Simpler:

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

Upvotes: 5

f6a4
f6a4

Reputation: 1782

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

Upvotes: 0

Related Questions