如何停止一个像无休止循环一样运行的应用程序.带有WPF中的一个按钮
本文关键字:一个 应用程序 带有 运行 按钮 WPF 循环 何停止 无休止 一样 | 更新日期: 2023-09-27 18:29:48
我有一个像无休止循环一样运行的应用程序。
如果我按下"停止跑步"按钮,我希望应用程序停止运行。
在控制台中,它将使用触发器Console.KeyAvailable(我想要这样的东西)。
主窗口.xaml:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Name="btnStart" Content="Run" HorizontalAlignment="Left" Height="46" Margin="186,248,0,0" VerticalAlignment="Top" Width="109" Click="btnStart_Click"/>
<TextBlock Name="OutputText" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="312,31,0,0" Height="204" Width="169" RenderTransformOrigin="0.495,0.511" />
<Button Content="Stop Running" HorizontalAlignment="Left" Height="46" Margin="326,248,0,0" VerticalAlignment="Top" Width="108" Click="Button_Click"/>
</Grid>
主窗口.xaml:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void btnStart_Click(object sender, RoutedEventArgs e)
{
APPexample Example = new APPexample();
Example.Run();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Example.StopRunning = true;
App.Current.Shutdown();
}
}
以运行APPexample的方式运行它,肯定会在UI线程上运行,因为您正在起诉WPF,这就是应用程序锁定的原因。
我宁愿使用后台线程来运行它,然后在启动方法中启动后台工作程序,然后在停止方法中要求它停止。
当UI线程运行时,启动按钮会阻塞它,因此您无法单击任何内容。请尝试下面的代码。虽然在不知道APPexample
是什么的情况下,我不能说它是否能工作
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void btnStart_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
APPexample Example = new APPexample();
Example.Run();
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Example.StopRunning = true;
App.Current.Shutdown();
}
}