How do you break a while loop with a WPF key press?

I saw answers to a question on how to exit a while loop with a keystroke for a console application and a winforms application, but not for a WPF application. So how do you do this? Thanks.

Ok, make it clear: Something like this does not work in a WPF (non-console) application. It throws a runtime error:

while(!Console.KeyAvailable) { //do work } 
+4
source share
2 answers

MainWindow.xaml

 <Window x:Class="WpfApplication34.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Width="525" Height="350"> <Grid> <TextBlock x:Name="tb" /> </Grid> </Window> 

MainWindow.xaml.cs

 public partial class MainWindow:Window { private int _someVal = 0; private readonly CancellationTokenSource cts = new CancellationTokenSource(); public MainWindow() { InitializeComponent(); Loaded += OnLoaded; } private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs) { KeyDown += OnKeyDown; while (!cts.IsCancellationRequested) { await Task.Delay(1000); // Some Long Task tb.Text = (++_someVal).ToString(); } } private void OnKeyDown(object sender, KeyEventArgs keyEventArgs) { if (keyEventArgs.Key == Key.A) cts.Cancel(); } } 

This is just a rough demonstration, just take the concept. The only thing that is characteristic of WPF here is a way to capture keystrokes. Everything else related to splitting a while loop is the same for a console application or wpf or winforms.

+1
source

You can create a na event in KeyDown Event in MainWindow and get KeyEventArgs e to find out which key was pressed.

 private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.A) { // set a flag to break the loop } } 
+1
source

Source: https://habr.com/ru/post/1492113/


All Articles