In WPF, the button is clicked multiple times to trigger the click solution. wpfclick
In WPF, you can click the button multiple times to trigger a click. The details are as follows:
DateTime lastClick = DateTime.Now; object obj = new object(); int i = 0; private void Button_Click(object sender, RoutedEventArgs e) { this.IsEnabled = false; var t = (DateTime.Now - lastClick).TotalMilliseconds; i++; lastClick = DateTime.Now; System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now); Thread.Sleep(2000); this.IsEnabled = true; }
The above Code does not solve the problem that the user clicks the button twice to trigger twice. Because the ui thread is single-threaded, this will cause the user to click twice in a row, it will call Button_Click again two seconds later. The output is as follows:
1207.069, 1; April 19, 2017 13:58:22
2055.1176, 2; April 19, 2017 13:58:24
Therefore, force the interface to refresh after this. IsEnabled = false; the Code is as follows:
private void Button_Click(object sender, RoutedEventArgs e) { this.IsEnabled = false; DispatcherHelper.DoEvents(); var t = (DateTime.Now - lastClick).TotalMilliseconds; i++; lastClick = DateTime.Now; System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now); Thread.Sleep(2000); this.IsEnabled = true; } public static class DispatcherHelper { [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void DoEvents() { DispatcherFrame frame = new DispatcherFrame(); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame); try { Dispatcher.PushFrame(frame); } catch (InvalidOperationException) { } } private static object ExitFrames(object frame) { ((DispatcherFrame)frame).Continue = false; return null; } }
DispatcherHelper. DoEvents (); this method forces the interface to be refreshed and the problem is solved.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.