zoukankan      html  css  js  c++  java
  • 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(); 
  • 相关阅读:
    C# 迭代器.NET实现—IEnumerable和IEnumerator
    Excel、CSV文件处理
    C# 读写ini文件
    SCARA——OpenGL入门学习五六(三维变换、动画)
    GDI与OpenGL与DirectX之间的区别
    SCARA——OpenGL入门学习四(颜色)
    SCARA——OpenGL入门学习三
    SQLite数据库表是否存在
    数据库SQL语句单引号、双引号的用法
    C# 委托与事件
  • 原文地址:https://www.cnblogs.com/andyzhao365/p/2225479.html
Copyright © 2011-2022 走看看