Solution to trigger click by clicking button button multiple times at the same time in WPF

  • 2021-09-16 06:42:53
  • OfStack

Solve the button button in WPF to trigger click by clicking it several times at the same time. For your reference, the specific contents 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 can't solve the problem that the user clicks the button twice to trigger twice, because the ui thread is single-threaded, so this will cause the user to click twice in succession, and then call Button_Click1 times after two seconds. The output is as follows:

1207.069, 1; April 19, 2017 13:58:22
2055.1176, 2; April 19, 2017 13:58:24

Therefore, this. IsEnabled = false; The interface is forced to refresh later, and 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.


Related articles: