我需要延迟检索 ToolStripTextBox
的 TextChanged
事件,以便在停止按键 x 秒后做一些事情..
我为 TextBox
找到了这个(并且有效)示例。
https://www.codeproject.com/Articles/20068/Custom-TextBox-that-Delays-the-TextChanged-Event
我试图将它转换为 ToolStripTextBox
,但出现此错误:
void DelayTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// stop timer.
DelayTimer.Enabled = false;
// set timer elapsed to true, so the OnTextChange knows to fire
TimerElapsed = true;
try
{
// use invoke to get back on the UI thread.
this.Invoke(new DelayOverHandler(DelayOver), null);
}
catch { }
}
'DelayToolStripTextBox' does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'DelayToolStripTextBox' could be found (are you missing a using directive or an assembly reference?)
ToolStripTextBox
没有“Invoke”方法..
有人能帮帮我吗?
提前致谢
最佳答案
为什么要使用一些外部代码?计时器可以轻松完成您的工作:
定义一个Timer
,它会在TextChange
时启动。如果 Timer
正在运行,它应该被重置。
如果达到 Timer.Intervall
,我们就知道我们没有得到新的输入,因为定时器没有重置。
现在 Timer
应该触发它的 Tick
事件。该事件应触发我们的方法,我们使用 t.Tick += ClearText;
将其绑定(bind)。
// your trigger
private void textBox1_TextChanged(object sender, EventArgs e)
{
StartEventAfterXSeconds();
}
private Timer t;
// your time-management
private void StartEventAfterXSeconds(int seconds = 10)
{
if (t != null)
{
t.Stop();
}
else
{
t = new Timer();
t.Tick += ClearText;
}
t.Interval = 1000 * seconds;
t.Start();
}
// You action
public void ClearText(object sender, EventArgs args)
{
this.textBox1.Text = null;
t.Stop();
}
如果你想使用多个这样的文本框,你应该把所有的东西都移到一个类中。
- 继承文本框
- 添加一个应该在延迟之后触发的事件。
- 构建一个启动计时器并由普通
TextChanged
事件触发的方法 - 实现触发新事件并停止计时器的 Tick-Method。
一些关于没有定时器的自定义事件的信息和它的滴答方法:simple custom event
public class TextBoxWithDelay : TextBox
{
public TextBoxWithDelay()
{
this.DelayInSeconds = 10;
this.TextChanged += OnTextChangedWaitForDelay;
}
public int DelayInSeconds { get; set; }
public event EventHandler TextChangedWaitForDelay;
private Timer t;
private void OnTextChangedWaitForDelay(object sender, EventArgs args)
{
if (t != null)
{
t.Stop();
}
else
{
t = new Timer();
t.Tick += DoIt;
}
t.Interval = 1000 * DelayInSeconds;
t.Start();
}
public void DoIt(object sender, EventArgs args)
{
if (TextChangedWaitForDelay != null)
{
TextChangedWaitForDelay.Invoke(sender, args);
t.Stop();
}
}
}
关于c# - ToolStripTextBox 延迟 TextChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48558801/