c# - 计时器事件导致表单无法平滑调整大小

标签 c# winforms

我的表单底部有一个网格控件,如果用户想要显示/隐藏它,它可以显示或隐藏。所以一种方法是很好地使用表单的 AutoSize 并将该网格的 Visuble 属性更改为 true 或 false,... 但我想让我们让它更酷一点!所以我希望表单的大小调整得慢一点,就像车库门一样!因此,我在表单上放置了一个计时器,并开始在计时器滴答作响时逐渐增加表单的高度...

当用户说显示/隐藏网格时,就像这样:

    timer1.Enabled = true;
    timer1.Start();

在timer_click事件中类似这样的事情:

    this.Height = this.Height + 5;
    if(this.Height -10 > ErrorsGrid.Bottom )
        timer1.Stop();

它确实有效,但仍然不完美。例如,它在一开始就滞后,停止调整大小,然后再次开始调整大小......那么现在考虑到这个想法,你建议我应该做哪些改变来使这个东西看起来和工作得更好?

最佳答案

尝试使用System.Timers.Timer来代替。您可以阅读有关可用 .net 计时器之间差异的更多信息 here ,但我认为你的问题归结为:

"[System.Windows.Forms.Timer] events raised by this timer class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class..."

这对于 System.Timers.Timer 来说不会是问题。只需确保将该对象的 SynchronizingObject 设置为您的表单,以便 elapsed 事件在 UI 线程上执行。

示例:

public partial class Form1 : Form
{
    System.Timers.Timer timer = new System.Timers.Timer(100);

    public Form1()
    {
        InitializeComponent();

        timer.AutoReset = true;
        timer.SynchronizingObject = this;
        timer.Elapsed += timer_Elapsed;
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        this.Height += 5;

        if (this.Height -10 > ErrorsGrid.Bottom)
            timer.Stop();
    }

    void button1_Click(object sender, EventArgs e)
    {
        timer.Start();
    }
}

关于c# - 计时器事件导致表单无法平滑调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905970/

相关文章:

c# - 为什么 CaSTLe Windsor 类型的工厂在使用不同参数创建时返回相同的实例

c# - C# 打印中的换页

C#:如何通过以某种方式从另一个线程发出信号,从主线程强制执行 "calling"方法

C#:将字符列表转换为字符串

c# - 选择数据的最佳方式是什么

c# - 为 LINQ 上下文禁用所有延迟加载或强制预加载

c# - C#构建日期为带前导0且没有分隔符的字符串

c# - 如何防止在c#中最大化无状态形式

c# - 如何在 C# 系统托盘应用程序中重复运行代码(如定时器)?

c# - TextBox - TextChanged 事件 Windows C#