在我的Powershell GUI中,我想按下一个按钮并打开记事本,而不会在后台关闭GUI。
对话框立即关闭,并显示以下代码
$button.Add_Click({Start-Process notepad.exe $file}) ;
使用-Wait时,对话框将保持打开状态,直到我关闭记事本,但仍然关闭
$button.Add_Click({Start-Process -Wait notepad.exe $file}) ;
使用变量时也会发生同样的情况
$button.Add_Click({& $notepad $file}) ;
以下是完整的代码块:
$file = '*\file.txt'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = "Don't close"
$form.Size = New-Object System.Drawing.Size(280,160)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedDialog'
$form.Topmost = $true
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(20,40)
$button.Size = New-Object System.Drawing.Size(160,23)
$button.Text = "button"
$button.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $button
$form.Controls.Add($button)
$button.Add_Click({Start-Process -Wait notepad.exe $file}) ;
$form.ShowDialog()
我要去哪里错了?
答案 0 :(得分:1)
这是因为您将按钮设置为表单的AcceptButton
以及获取DialogResult的控件。
只需删除两行(为显示哪一行,我在下面添加注释的代码)。
然后,也不要使用-Wait
上的Start-Process
开关。
调整后的代码:
$file = 'D:\blah.txt'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = "Don't close"
$form.Size = New-Object System.Drawing.Size(280,160)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedDialog'
$form.Topmost = $true
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(20,40)
$button.Size = New-Object System.Drawing.Size(160,23)
$button.Text = "button"
# drop these two lines
# $button.DialogResult = [System.Windows.Forms.DialogResult]::OK
# $form.AcceptButton = $button
$form.Controls.Add($button)
# do not use the -Wait parameter on Start-Process here
$button.Add_Click({Start-Process notepad.exe $file}) ;
$form.ShowDialog()
$form.Dispose()