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);
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.
source share