This article mainly introduces in detail the solution to the problem of clicking the button button multiple times at the same time in WPF. It has a certain reference value. Interested friends can refer to
Solutions in WPF The method of clicking the button button multiple times at the same time to trigger the click is for your reference. The specific content is 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 cannot solve the problem of the user clicking the button twice to trigger the click twice, because the UI thread is single-threaded. So this will cause the user to click twice in a row, and Button_Click will be called 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
So to force the interface 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 will force the interface to refresh and the problem will be solved.
The above is the detailed content of Teach you the instance method of triggering click by clicking the button button multiple times at the same time in WPF. For more information, please follow other related articles on the PHP Chinese website!