如何在PowerShell脚本的WPF消息框中添加复制按钮
如何在PowerShell脚本的WPF消息框中添加复制按钮
我明白你的需求啦——你现在的WPF消息框只能显示VPN用户名和OK按钮,想要加个一键复制用户名的按钮,而且不想脱离原脚本的框架对吧?没问题,咱们不用深入WPF复杂知识,只需要调整一下消息框的内容结构,把文本框和复制按钮放到同一个容器里就能实现。
修改思路
- 保留你原来读取VPN用户名、加载WPF程序集的核心代码,这部分完全不用改;
- 新增一个垂直布局容器(StackPanel),把原来的RichTextBox和复制按钮都放进这个容器里;
- 给复制按钮绑定点击事件,点击时直接把用户名复制到系统剪贴板,还可以加个小提示反馈用户。
修改后的完整脚本
# Read content of VPN_username.txt, if it exists. if (Test-Path -Path "$env:SystemDrive\Temp\VPN_username.txt") { $VPNUserName = Get-Content -Path "$env:SystemDrive\Temp\VPN_username.txt" -Force } # Load WPF assembly Add-Type -AssemblyName PresentationFramework Add-Type -AssemblyName WindowsBase # 剪贴板功能需要依赖这个程序集 # Create a richtextbox to display the completion summary with hyperlinks $RTB = New-Object System.Windows.Controls.RichTextBox $RTB.Padding = 5 $RTB.IsDocumentEnabled = $true $RTB.IsReadOnly = $true $RTB.BorderThickness = 0 $RTB.MaxWidth = 370 $RTB.FontFamily = "Segui" $RTB.FontSize = 14 $FlowDocument = New-Object System.Windows.Documents.FlowDocument $Paragraph = New-Object System.Windows.Documents.Paragraph $Run = New-Object System.Windows.Documents.Run $Run.Text = "The VPN username that you last used is $VPNUserName" $Paragraph.AddChild($Run) $FlowDocument.AddChild($Paragraph) $RTB.AddChild($FlowDocument) # 创建复制按钮并设置样式 $copyButton = New-Object System.Windows.Controls.Button $copyButton.Content = "复制用户名" $copyButton.Margin = "0,10,0,0" # 和上方文本框拉开间距,视觉更舒服 $copyButton.Padding = "8,4" $copyButton.Add_Click({ # 点击按钮时将用户名复制到剪贴板 [System.Windows.Clipboard]::SetText($VPNUserName) # 可选:弹出小提示告诉用户复制成功 [System.Windows.MessageBox]::Show("用户名已复制到剪贴板!", "提示", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information) }) # 创建垂直布局容器,把文本框和按钮整合在一起 $container = New-Object System.Windows.Controls.StackPanel $container.Orientation = "Vertical" $container.Margin = 10 # 给整个容器加内边距,避免内容贴边 $container.AddChild($RTB) $container.AddChild($copyButton) # Display the messagebox. New-WPFMessageBox -Content $container -Title "Cisco Secure Client Upgrade" -TitleFontSize 24 -TitleBackground MidnightBlue -TitleTextForeground White -Sound 'Windows Notify'
关键修改说明
- 额外添加了
Add-Type -AssemblyName WindowsBase:因为WPF的剪贴板功能需要依赖这个程序集; - 用
StackPanel作为容器:让文本和按钮垂直排列,完美适配原脚本的New-WPFMessageBox函数; - 按钮点击事件逻辑:直接调用WPF剪贴板API复制用户名,可选的提示弹窗能给用户更明确的操作反馈,不需要的话可以直接删掉那行代码。
备注:内容来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

