PS帮助KeyDown和点击功能和哈希表

时间:2016-12-25 21:59:30

标签: function powershell listbox click add

我有这样的事情:

#initialize System.Drawing and System.Windows.Forms
#$form = New-Object System.Windows.Forms.Form , $form.text, $form.Size etc
#$listBox = New-Object System.Windows.Forms.ListBox , $listBox.Location etc

$form.KeyPreview = $True

$form.Add_KeyDown({if ($_.KeyCode -eq "Enter"){ 
#call func passing $item value to the currentItemSelected parameter of func
$item=$listBox.SelectedItem;(Func -currentItemSelected $item)}}) 

$form.Add_KeyDown({if ($_.KeyCode -eq "Escape"){$form.Close()}})

$hashT1 = Get-Content -raw "path\hashT.txt" | ConvertFrom-StringData
$hashT2 = Get-Content -raw "path\hashT2.txt" | ConvertFrom-StringData

#arg is recieved from Btn.Add_Click(), btn1 clicked arg1 = $hashT1, btn2 = $hashT2 ...
function PopList($arg1){
$listBox.Items.Clear()
foreach ($game in $arg1.GetEnumerator() | sort Name){
$listBox.Items.Add("{0}" -f $game.Key)}

##Function recieve $hashT1 or any table I state when I click a Button
##and recieve the listbox.SelectedItem value when I press enter
##Write-Host is just to check if the variables recieved the correct info
function Func($currentHashT, $currentItemSelected ){
Write-Host $currentHashT.$currentItemSelected}

$btn1 = New-Object System.Windows.Forms.Button
#{.location, .size, .text...}
#PopList fill list with $hashT1 keys and Func $currentHashT should be $hashT1 'cause I'm
#passing $hashT1 as argument
$btn1.Add_Click({PopList $hashT1; Func -currentHashT $hashT1})
$form.Controls.Add($bt1)

$btn2 = New-Object System.Windows.Forms.Button
#{.location, .size, .text...}
#PopList fill list with $hashT2 keys and Func $currentHashT should be $hashT2 'cause I'm
#passing $hashT2 as argument
$btn2.Add_Click({PopList $hashT2; Func -currentHashT $hashT2})
$form.Controls.Add($btn2)

$form.Controls.Add($listBox)
$form.Add_Shown({$form.Activate()})
[void] $form.ShowDialog()

因此,我想点击一个按钮,填写我的列表,选择项目,然后按回车键,然后写入 - 托管我说明我想要的KEY的VALUE。 因此,如果我单击btn1,从列表中选择一个项目并按Enter键将写入 - 承载$ hashT1.'KEY'的值,例如:
$ hashT1 = @ {“File 1”=“Path \ File1.bin”; “文件2”=“Path \ File2.cue”} 点击btn1,填充列表框,包含2行,“文件1”和“文件2” 现在选择其中任何一个,文件2 按回车键,它将写入主机:Path \ File2.cue

我得到的结果是:
“空行”后跟选定项目值

如果我将我的Func写入Write-Host $ currentHashT.'File 2',它就会工作 如果我将我的Func写入Write-Host $ hashT1。$ currentItemSelected它会工作
但是,如果我这样做,我将不得不为我想要添加的每个按钮创建一个函数,我可以按照我想要的方式执行此操作吗?使用根据我想要的变化的变量...
感谢您阅读我的问题。

1 个答案:

答案 0 :(得分:0)

问题不是变量改变了值,问题是你试图用两个参数来调用函数,比如

function add ($a, $b) {
    write-host ($a + $b)
}

add -a 4

add -b 5

并期望以某种方式只调用该函数一次,并打印9.这是永远不会起作用。

您可以通过将$currentHashT保留在父作用域中来执行此操作,并且该函数仅引用它而不是通过参数传入它:

function add($b) {
    write-host ($firstNUm + $b)
}

$n = 4
$firstNUm = $n
add -b 5

$n = 5
$firstNUm = $n
add -b 5

否则你必须完全重新设计它。