为Powershell脚本中的按钮指定键盘快捷键

时间:2015-12-08 00:53:00

标签: forms powershell button keyboard-shortcuts shortcut-key

我想要做的是为快捷键分配一个按钮,例如$ TurnOnButton作为键" Q"和$ TurnOffButton作为键" W"在我的键盘上。

所以基本上,在我下面的例子中。当脚本运行并且表单存在时,我可以按下按钮" Q"在我的键盘上运行计算器,然后按下按钮" W"终止它。

PowerShell可以实现吗?

代码示例:

Add-Type -AssemblyName System.Windows.Forms

function Return-TurnOff
{
    $x = Stop-Process -ProcessName calc
    $x
}

function Return-TurnOn
{
    $x = Start-Process calc
    $x
}

$form = New-Object System.Windows.Forms.Form 
$form.Text = "Title of the form"
$form.Size = New-Object System.Drawing.Size(300,200) 
$form.minimumSize = New-Object System.Drawing.Size(300,200) 
$form.maximumSize = New-Object System.Drawing.Size(300,200) 
$form.StartPosition = "CenterScreen"

$TurnOffButton = New-Object System.Windows.Forms.Button
$TurnOffButton.Location = New-Object System.Drawing.Point(10,125)
$TurnOffButton.Size = New-Object System.Drawing.Size(55,25)
$TurnOffButton.Text = "Turn Off"
$TurnOffButton.Add_Click({Return-TurnOff})
$form.AcceptButton = $TurnOffButton
$form.Controls.Add($TurnOffButton)

$TurnOnButton = New-Object System.Windows.Forms.Button
$TurnOnButton.Location = New-Object System.Drawing.Point(10,65)
$TurnOnButton.Size = New-Object System.Drawing.Size(55,25)
$TurnOnButton.Text = "Turn On"
$TurnOnButton.Add_Click({Return-TurnOn})
$form.AcceptButton = $TurnOnButton
$form.Controls.Add($TurnOnButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(215,125)
$CancelButton.Size = New-Object System.Drawing.Size(55,25)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,15) 
$label.Size = New-Object System.Drawing.Size(280,20) 
$label.Text = "Label for textbox:"
$form.Controls.Add($label) 

$textBox = New-Object System.Windows.Forms.TextBox 
$textBox.Location = New-Object System.Drawing.Point(10,35) 
$textBox.Size = New-Object System.Drawing.Size(260,20) 
$form.Controls.Add($textBox) 

$form.Topmost = $True

$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()

1 个答案:

答案 0 :(得分:2)

如果您不介意按钮上的标签包含与按钮对应的字母并按下Alt键,那么这很简单,只需输入'&'即可。在按钮文本中的字母之前,您希望成为加速器:

$TurnOnButton.Text = "Turn O&n"
$TurnOffButton.Text = "Turn O&ff"

将使Alt-N执行Turn On,Alt-F执行Turn Off。

更复杂的解决方案是注册键盘按下,但无论是否按下Alt,它都可以让您处理任何击键。 $form|gm -MemberType event key*会显示名称以“Key”开头的事件。然后,您可以谷歌了解如何使用WinForms处理来自Powershell的事件。