C# 提供一个Winform可控的延迟触发按钮

这篇博客介绍了一个自定义的DelayButton控件,它允许在点击按钮后延迟执行事件处理,期间不会占用UI线程,避免了界面卡死。用户可以设置延迟时间和是否控制按钮的可用性。示例代码展示了如何使用Task.Run和Invoke来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果描述:

当点击一个按钮时,会自动延时您所以设定的时间,然后才执行该按钮事件,这个过程不会占用UI线程,不会卡死。

直接给您传上代码,您可以自行测试一下效果:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Windows.Forms
{
    /// <summary>
    /// 表示可控的延迟触发按钮
    /// </summary>
    /// <creator>marc</creator>
    public class DelayButton : Button
    {
        /// <inheritdoc cref="DelayButton" path="/summary"/>
        public DelayButton() { }

        /// <summary>
        /// 延迟多久才触发按钮事件,默认0,单位毫秒
        /// </summary>
        [Browsable(true)]
        [Category("Zhongzhou")]
        [DefaultValue(0)]
        [Description("表示延迟多久才触发按钮事件,默认0,单位毫秒")]
        public int Interval { get; set; } = 0;

        /// <summary>
        /// 是否控制按钮的可用性。默认启用控制,效果是当按下按钮时变灰色,事件完成后恢复可用状态
        /// </summary>
        [Browsable(true)]
        [Category("Zhongzhou")]
        [DefaultValue(true)]
        [Description("表示是否控制按钮的可用性。默认启用控制,效果是当按下按钮时变灰色,事件完成后恢复可用状态")]
        public bool UseEnable { get; set; } = true;

        /// <inheritdoc/>
        protected override void OnClick(EventArgs e)
        {
            if (UseEnable)
            {
                this.Enabled = false;
            }

            Task.Run(async () =>
            {
                await Task.Delay(this.Interval);

                this.Invoke(new Action(() =>
                {
                    base.OnClick(e);

                    if (UseEnable)
                    {
                        this.Enabled = true;
                    }
                }));
            });
        }
    }
}

祝您用餐愉快

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值