使用以下代码为表单设置热键按下事件,但是当按下热键时,系统会发出警报声,为什么?
此外,如何设置多个修饰键,例如ctrl + alt + shift + Q
$form1_KeyDown = [System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
if ($_.Alt -and $_.KeyCode -eq 'Q')
{
Write-Host 'Alt-Q pressed'
}
}
答案 0 :(得分:0)
我不知道为什么在按下热键时会听到系统提示音,但这可能与将KeyEventHandler添加到表单中的方式有关。
使用$form1.Add_KeyDown({..})
不会给我带来任何问题:
$form1.Add_KeyDown({
# create a small array to capture the modifier keys used
$modifiers = @()
if ($_.Shift) { $modifiers += "Shift" }
if ($_.Alt) { $modifiers += "Alt" }
if ($_.Control) { $modifiers += "Control" }
# using that array, build part of the output text
$modkeys = ''
if ($modifiers.Count) {
$modkeys = '{0} ' -f ($modifiers -join ' + ')
}
# instead of building up a string 'Shift + Control + Alt', like above, you can also use
# the $_.Modifiers property and replace the commas by a plus sign like this:
# $modkeys = $_.Modifiers -replace ', ', ' + '
# these are the keys you want to react upon as example
# here all keys pressed simply do the same thing, namely display what was pressed,
# so we can shorten the code to simply test if any of the keys in the
# array correspond with the key the user pressed.
if ('Q','A','F1','Escape','NumLock' -contains $_.KeyCode) {
# we create the output string by making use of the '-f' Format operator in POwershell.
# you can read more about that here for instance:
# https://social.technet.microsoft.com/wiki/contents/articles/7855.powershell-using-the-f-format-operator.aspx
Write-Host ('{0}{1} pressed' -f $modkeys, $_.KeyCode)
# The same could have been done with something like:
# Write-Host ($modkeys + ' ' + $_.KeyCode + ' pressed')
# or
# Write-Host "$modkeys $($_.KeyCode) pressed"
}
})