• WPF 中实现 Winfrom 中 Application.DoEvents() 方法


    熟悉 Winfrom 中 Application.DoEvents() 方法的朋友一定用过此方法,此方法可以立即处理当前在消息队列中的所有 Windows 消息。 如在一个按钮单击事件中,需要每一秒改变label的Text属性,如下代码:

    1.      private void button1_Click(object sender, EventArgs e) 
    2.      { 
    3.          for (int i = 0; i < 50; i++) 
    4.              Thread.Sleep(500); 
    5.              this.label1.Text = i.ToString(); 
    6.      } 

    编译运行,单击按钮,你并不会见到lable一直改变,等到执行完,你只会看见49。而加上 Application.DoEvents() 方法则可以看到一直更改的文本

    1. private void button1_Click(object sender, EventArgs e) 
    2.     for (int i = 0; i < 50; i++) 
    3.  
    4.         Thread.Sleep(500); 
    5.         this.label1.Text = i.ToString(); 
    6.         Application.DoEvents(); 
    7.  

    好了,废话不多说了,不明白的可以参考 Application.DoEvents 方法

          在 WPF 中没有 Application.DoEvents() 方法,看下面实现代码:

    1. public static class DispatcherHelper 
    2.     [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] 
    3.     public static void DoEvents() 
    4.     { 
    5.         DispatcherFrame frame = new DispatcherFrame(); 
    6.         Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame); 
    7.         try { Dispatcher.PushFrame(frame); } 
    8.         catch (InvalidOperationException) { } 
    9.     } 
    10.     private static object ExitFrames(object frame) 
    11.     { 
    12.         ((DispatcherFrame)frame).Continue = false
    13.         return null
    14.     } 

    调用:

    1. DispatcherHelper.DoEvents(); 
  • 相关阅读:
    约瑟夫问题
    再谈Bellman-Ford
    Uva 11478 Halum操作
    Uva 11090 在环中
    Bellman-Ford
    Uva 10537 过路费
    Uva 10917
    LA 3713 宇航员分组
    2-SAT
    LA 3211 飞机调度
  • 原文地址:https://www.cnblogs.com/andyzhao365/p/2225479.html
Copyright © 2020-2023  润新知