第一次在Powershell v3中尝试自定义对话框。我想在表单中添加一个浏览按钮。我有它所以它显示浏览按钮,但我似乎无法弄清楚我们从OpenFileDialog对象获取文件名并让它出现在objTextBox字段中的部分。我已经研究过,但似乎找不到任何解释这部分过程的文章。
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Name = 'Text1'
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
#File Browser Code.
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
}
$browse_button = New-Object system.Windows.Forms.Button
$browse_button.Text = "Choose...."
$browse_button.Location = New-Object System.Drawing.Size(10,75)
$browse_button.Size = New-Object System.Drawing.Size(100,27)
$browse_button.Add_Click({[void]$FileBrowser.ShowDialog()})
$objForm.Controls.Add($browse_button)
答案 0 :(得分:1)
我想我的处理方式略有不同。我创建了一个显示“浏览文件”对话框并输出字符串的函数(我只是将其保留在手边)。然后为Add_Click设置文本框的值=该函数。类似的东西:
Function Get-FilePath{
[CmdletBinding()]
Param(
[String]$Filter = "|*.*",
[String]$InitialDirectory = "C:\")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Name = 'Text1'
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
$browse_button = New-Object system.Windows.Forms.Button
$browse_button.Text = "Choose...."
$browse_button.Location = New-Object System.Drawing.Size(10,75)
$browse_button.Size = New-Object System.Drawing.Size(100,27)
$browse_button.Add_Click({$objTextBox.Text = Get-FilePath -InitialDirectory "$env:UserProfile\Desktop"})
$objForm.Controls.Add($browse_button)
$browse_button.Text = "Choose...."
$browse_button.Location = New-Object System.Drawing.Size(10,75)
$browse_button.Size = New-Object System.Drawing.Size(100,27)
$browse_button.Add_Click({[void]$FileBrowser.ShowDialog()})
$objForm.Controls.Add($browse_button)