2010-10-11 99 views
1

我使用下面的PowerShell 2.0的代码从VB输入框输入抢:如何使用PowerShell将焦点设置到输入框?

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

有时候,当我运行它出现在活动窗口后面的输入框。有没有办法让输入框成为最高?或者一个简单的方法来获得它的句柄,并使用setforegroundwindow?

谢谢!

回答

4

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

$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函数。

+0

谢谢,这个问题的答案帮助了很多! – Evan 2010-10-12 15:58:07

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 
0

如果为它种使它“莫代尔”输入框中的默认值,这样的事情:

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