效果描述:
当点击一个按钮时,会自动延时您所以设定的时间,然后才执行该按钮事件,这个过程不会占用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;
}
}));
});
}
}
}
祝您用餐愉快