继续我的评论。
控制台主机有点不灵活,具体取决于您在本机上所做的事情。该“X”与 PowerShell 会话/进程有关,而不是与其中运行的代码有关。因此,为什么 CRTL+C 有效,因为您要停止代码运行,而不是 PowerShell 会话/进程。
这里有几种方法可以让您考虑您的选择。
###############################################################################
#region Begin initialize environment #
###############################################################################
# Initialize GUI resources
Add-Type -AssemblyName System.Drawing,
PresentationCore,
PresentationFramework,
System.Windows.Forms,
microsoft.VisualBasic
[System.Windows.Forms.Application]::EnableVisualStyles()
###############################################################################
#endregion End initialize environment #
###############################################################################
# Prevent the MessageBox UI from closing until an entry is made
while (
($UserEntry = [Microsoft.VisualBasic.Interaction]::
InputBox('Enter a Host/User', 'Add Item')) -eq ''
)
{
[System.Windows.Forms.MessageBox]::
Show(
'Entry cannot be empty',
"Error on close" ,
0,
[System.Windows.MessageBoxImage]::Error
)
}
"You entered $UserEntry"
或用于更精细控制的完整自定义表单
# Initialize the form object
$form = New-Object System.Windows.Forms.Form
# Define form elements
$form.Text = 'Data Entry'
$txtUserInput = New-Object system.Windows.Forms.TextBox
$txtUserInput.multiline = $false
$txtUserInput.width = 120
$txtUserInput.height = 20
$txtUserInput.location = New-Object System.Drawing.Point(40,29)
$txtUserInput.Font = 'Microsoft Sans Serif,10'
$form.controls.AddRange(@(
$txtUserInput
)
)
# Evaluate form events
$form.Add_Closing(
{
param
(
$Sender,$Event
)
$result = [System.Windows.Forms.MessageBox]::Show(
'Are you sure you want to exit?',
'Close',
[System.Windows.Forms.MessageBoxButtons]::YesNo
)
if ($result -ne [System.Windows.Forms.DialogResult]::Yes)
{$Event.Cancel = $true}
})
# Start the form
$form.ShowDialog() | Out-Null
# Resource disposal
$form.Dispose()