【发布时间】:2018-05-30 01:39:24
【问题描述】:
我最初并没有计划实现 BusyIndicator,但我意识到我的 Powershell 脚本需要一些时间来执行,这可能会导致用户混淆。似乎没有任何教程展示如何在 C# 中将 BusyIndicator 与 Powershell 脚本结合使用。 This 是一个很棒的教程,因为它是由 WPF 扩展工具包的作者编写的,但它不是我需要的。
这就是我所拥有的。为简洁起见,代码被截断:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void imageBtn_Click(object sender, RoutedEventArgs e)
{
Button imgBtn = sender as Button;
string appToCheck = GetSubString(imgBtn.Name);
switch(appToCheck)
{
case "weather":
InvokePowerShell(appToCheck);
break;
case "news":
//DO THE SAME FOR ALL CASES
break;
//17 more cases follow
}
}
private string GetSubString(string buttonName)
{
int index = buttonName.IndexOf('B');
return buttonName.Substring(0, index);
}
private void InvokePowerShell(string str)
{
str = char.ToUpper(str[0]) + str.Substring(1);
PowerShell ps = PowerShell.Create();
ps.AddScript("Get-AppxPackage | Select Name | Where-Object ($_.Name -like '*" + str + "*'}");
_busyIndicator.IsBusy = true;
ps.BeginInvoke<PSObject>(null, new PSInvocationSettings(), ar =>
{
try
{
var psOutput = ps.EndInvoke(ar);
this.Dispatcher.Invoke(() => _busyIndicator.IsBusy = false);
foreach (PSObject item in psOutput)
{
if (item.Equals(String.Empty))
{
MessageBox.Show(str + " is not installed so cannot be removed.");
}
else
{
if (MessageBox.Show("This cannot be undone.\nContinue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
{
//DO NOTHING
}
else
{
//TODO Remove the app
MessageBox.Show(str + " successfully removed.");
}
}
}
}
finally
{
//dispose of it
ps.Dispose();
}
}, null);
}
}
}
我已经在我的 XAML 中设置了 BusyIndicator:
<toolkit:BusyIndicator x:Name="_busyIndicator" IsBusy="False" BusyContent="One moment....">
<!-- Insert the rest of my markup here -->
</toolkit:BusyIndicator>
我还将有一个更长的方法来删除应用程序中列出的所有内容,所以我肯定会想要这个指标。我尝试按照上面链接中给出的教程进行操作,但我遇到了我的 foreach 循环超出范围的问题。
我尝试使用异步 BeginInvoke() 方法无济于事。忙碌指示灯一直亮着,就像这样:
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject>(outputCollection);
while (result.IsCompleted == false)
{
_busyIndicator.IsBusy = true;
}
//Then my foreach loop shown above with the if statements and MessageBox notifications
我对此很陌生。任何帮助将不胜感激。
【问题讨论】:
标签: c# wpf powershell busyindicator