如何使用PowerShell将焦点设置到输入框?

时间:2010-10-11 22:59:31

标签: powershell

我正在使用以下PowerShell 2.0代码从vb输入框中获取输入:

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$name = [Microsoft.VisualBasic.Interaction]::InputBox("What is your name?", "Name", "bob")

有时当我运行它时,输入框会出现在活动窗口的后面。有没有办法让输入框最顶端?或者一个简单的方法来获得它的处理并只使用setforegroundwindow?

谢谢!

3 个答案:

答案 0 :(得分:5)

考虑到InputBox调用是模态的,我不知道如何轻松地做到这一点,所以你不能轻易地尝试找到窗口句柄并在该窗口上执行set-foreground(除非你尝试使用后台作业)。而不是使用这个VisualBasic文本输入框,如何使用WPF / XAML“滚动自己的”实现。它非常简单,但它确实需要WPF,必要时由PowerShell 2.0安装。

$Xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window"
        Title="Name" Height="137" Width="444" MinHeight="137" MinWidth="100"
        FocusManager.FocusedElement="{Binding ElementName=TextBox}"
        ResizeMode="CanResizeWithGrip" >
    <DockPanel Margin="8">
        <StackPanel DockPanel.Dock="Bottom" 
                    Orientation="Horizontal" HorizontalAlignment="Right">
            <Button x:Name="OKButton" Width="60" IsDefault="True" 
                    Margin="12,12,0,0" TabIndex="1" >_OK</Button>
            <Button Width="60" IsCancel="True" Margin="12,12,0,0" 
                    TabIndex="2" >_Close</Button>
        </StackPanel>
        <StackPanel >
            <Label x:Name="Label" Margin="-5,0,0,0" TabIndex="3">Label:</Label>
            <TextBox x:Name="TextBox" TabIndex="0" />
        </StackPanel>
    </DockPanel>
</Window>
'@

if ([System.Threading.Thread]::CurrentThread.ApartmentState -ne 'STA')
{
    throw "Script can only be run if PowerShell is started with -STA switch."
}

Add-Type -Assembly PresentationCore,PresentationFrameWork

$xmlReader = [System.Xml.XmlReader]::Create([System.IO.StringReader] $Xaml)
$form = [System.Windows.Markup.XamlReader]::Load($xmlReader)
$xmlReader.Close()

$window = $form.FindName("Window")
$window.Title = "My App Name"

$label = $form.FindName("Label")
$label.Content = "What is your name?"

$textbox = $form.FindName("TextBox")

$okButton = $form.FindName("OKButton")
$okButton.add_Click({$window.DialogResult = $true})

if ($form.ShowDialog())
{
    $textbox.Text
}

这可以很容易地包含在Read-GuiText函数中。

答案 1 :(得分:2)

如果你为输入框设置了一个默认值,它会使它成为&#34; modal&#34;,就像这样:

$response = [Microsoft.VisualBasic.Interaction]::InputBox("Do you want to include servers in MANUAL REBOOT group ? If YES, please type: Include MANUAL reboot group","Warning!!!","")   

答案 2 :(得分:0)

Sub SetInputBoxFocus()
    System.Threading.Thread.Sleep(300)
    Microsoft.VisualBasic.AppActivate("Title)
    ''Console.WriteLine("Setting focus ") '"
End Sub

Dim strPW as String = ""
Dim tsStartInfo As New System.Threading.ThreadStart(AddressOf SetInputBoxFocus)
Dim tBackgroundJob As New System.Threading.Thread(tsStartInfo)
tBackgroundJob.Start()
strPW = Microsoft.VisualBasic.InputBox("Prompt: ", "Title", "", -1, -1)
tBackgroundJob = Nothing
tsStartInfo = Nothing