Powershell中的GUI变量

时间:2016-04-29 16:45:48

标签: windows powershell

我希望设置一个GUI来确定首次设置应用程序的下一步。我最初使用批处理编写了整个程序,但希望看起来更加用户友好。该程序基本上卸载计算机制造商在其计算机上加载并安装一些有用程序的英国媒体报道。这是我第一次使用PowerShell。这就是我到目前为止所做的:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Pauk Inc."
$objForm.Size = New-Object System.Drawing.Size(300,175) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
{$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
{$objForm.Close()}})

$YesButton = New-Object System.Windows.Forms.Button
$YesButton.Location = New-Object System.Drawing.Size(70,95)
$YesButton.Size = New-Object System.Drawing.Size(75,23)
$YesButton.Text = "Sure"
$YesButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($YesButton)

$NoButton = New-Object System.Windows.Forms.Button
$NoButton.Location = New-Object System.Drawing.Size(155,95)
$NoButton.Size = New-Object System.Drawing.Size(75,23)
$NoButton.Text = "No Thanks"
$NoButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($NoButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(55,50) 
$objLabel.Size = New-Object System.Drawing.Size(280,25) 
$objLabel.Text = "Would you like to install Anti Virus?"
$objForm.Controls.Add($objLabel)  

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

$x

基本上我要做的就是安装AV,如果他们点击"当然",如果他们点击"不,谢谢"。

2 个答案:

答案 0 :(得分:2)

如果你只是在是/否响应之后,MessageBox需要更少的代码。

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

[System.Windows.Forms.DialogResult]$result = [System.Windows.Forms.MessageBox]::Show("Would you like to install anti-virus?", "Install Anti-Virus?", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question, [System.Windows.Forms.MessageBoxDefaultButton]::Button2)

if ($result -eq ([System.Windows.Forms.DialogResult]::Yes))
{
    # User selected yes.
}
else
{
    # User selected no.
}

答案 1 :(得分:0)

您可以像在任何Windows窗体应用中一样执行此操作。您还没有为按钮设置DialogResult,因此单击这些按钮时无法区分按钮。只需用以下代码替换最后一行:

$YesButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$result = $objForm.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    Write-Host "Installing..."
}