1. Use Xaml create application interfaces
Open visual studio, create a new project, select Visual C # → Wpf application has been installed templates.
When you finish creating, we get the application interface as shown in the following figure.
wpf xaml interface is based on language design, but without having to learn xaml, you can also use the various controls in the toolbox drag a nice layout (just like drag winform controls the same). Coupled with the properties panel, modify the properties of individual controls, it is easy to get a GUI interface also seen in the past.
Save the project. MainWindows.xaml found in the directory of the project, which is a copy, this document will become the xaml file powershell script GUI layout applications.
## 2. Write powershell script
New powershell script.
First reference wpf framework / core assembly, making wpf powershell scripts have the ability to create applications.
Add-type -AssemblyName presentationframework, presentationcore
Then create wpf object.
$wpf = @{ }
In the script reads xaml file
$x = Split-Path -Parent $MyInvocation.MyCommand.Definition $path = $x + ".\MainWindow.xaml" $inputXAML = Get-Content -Path $path $inputCleanXAML = $inputXAML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace 'x:Class=".*?"','' -replace 'd:DesignHeight="\d*?"','' -replace 'd:DesignWidth="\d*?"',''
几个说明:
$x是该powershell脚本所在文件夹的绝对路径,我将MainWindows.xaml放在与powershell脚本同级的文件夹下,使用 $MyInvocation.MyCommand.Definition获取当前运行脚本所在路径, Split-Path -Parent $MyInvocation.MyCommand.Definition即可获得当前运行脚本所在的文件夹路径。
由于powershell只支持对xml的解析,所以需要对xaml稍微修改一下,使用-replace批量替换掉多余的字符。
$inputCleanXAML = $inputXAML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace 'x:Class=".*?"','' -replace 'd:DesignHeight="\d*?"','' -replace 'd:DesignWidth="\d*?"',''
所有的xaml文件都可以使用这条语句来替换成xml。
紧接着使用xmlReader解析xml,创建窗体。
[xml]$xaml = $inputCleanXAML $reader = New-Object System.Xml.XmlNodeReader $xaml $tempform = [Windows.Markup.XamlReader]::Load($reader)
遍历完xml的节点后,调用$wpf.MainWindow.ShowDialog()就可以显示GUI窗体了。
此时我们点击窗体的按钮,窗体还不会有反应,接下来添加交互逻辑。
添加如下语句
$wpf.Confirm.add_Click({ #TODO... })
(在块内添加单击按钮时你所需要执行的逻辑。)
注意:我在创建wpf引用界面时,创建了一个名为“Confirm”的按钮,所以这里的add_Click({})对应的就是该按钮的点击时引发的事件。
保存powershell脚本文件,点击运行,我们即可以得到一个GUI程序了,如下图:
这个powershell脚本是我写的一个文本解析器,先点击More...按钮打开文件选择框,选择一个*.mod的文本文件,然后点击确定生成按钮获得变量列表--一个csv文件。
你可以在*https://github.com/Afuness/PowershellLab/tree/master/GUI*获取源代码。