2010-10-11 103 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!!!","") 
相關問題