zoukankan      html  css  js  c++  java
  • WPF中button按钮同时点击多次触发click解决方法

            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;
            }

    以上代码并没法解决用户点击两次按钮触发两次的问题,因为ui线程是单线程的,所以这个这样会导致用户连续点击两次,会两秒后又调用Button_Click一次,输出如下:

    1207.069,1;2017年4月19日 13:58:22
    2055.1176,2;2017年4月19日 13:58:24

    所以要在this.IsEnabled = false;后面强制界面刷新,代码如下:

       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();这个方法会强制界面刷新,问题就解决了

  • 相关阅读:
    分布式系统理论基础
    分布式系统理论基础
    RPC框架实现
    分布式服务协调员zookeeper
    LSM Tree存储组织结构介绍
    协程 及 libco 介绍
    回顾2013——新的旅程
    从prototype beandefinition 谈 spring 的关闭流程和 prototype 的特性
    调研 中央空调 地暖 水暖
    物联网安全设计
  • 原文地址:https://www.cnblogs.com/liningit/p/6733193.html
Copyright © 2011-2022 走看看