c# 4.0 - How do you break a while loop with a keypress in WPF? -
i've seen answers question of how break out of while loop keypress console app , winforms app not wpf app. so, uh, how do it? thanks.
okay, let's elaborate: doesn't work in wpf (non-console) app. throws runtime error:
while(!console.keyavailable) { //do work }
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); // long task tb.text = (++_someval).tostring(); } } private void onkeydown(object sender, keyeventargs keyeventargs) { if (keyeventargs.key == key.a) cts.cancel(); } } it's rough demo, take concept. thing specific wpf here manner of capturing key-press. else relating breaking while loop same across console app or wpf or winforms.
Comments
Post a Comment