你能为我指出正确的方向吗?我试图在按下表单按钮时触发循环。
//pseudocode
While (button1 is pressed)
value1 += 1
当然,当释放按钮时停止循环
为了避免使用线程,您可以添加Timer表单/控件上的组件,只需在鼠标按下时启用它并在鼠标按下时禁用它。然后将通常放入循环内的代码放入 Timer_Tick 事件中。如果您想使用 System.Timers.Timer,则可以使用 Timer.Elapsed 事件。
示例(使用 System.Timers.Timer):
using Timer = System.Timers.Timer;
using System.Timers;
using System.Windows.Forms;//WinForms example
private static Timer loopTimer;
private Button formButton;
public YourForm()
{
//loop timer
loopTimer = new Timer();
loopTimer.Interval = 500;/interval in milliseconds
loopTimer.Enabled = false;
loopTimer.Elapsed += loopTimerEvent;
loopTimer.AutoReset = true;
//form button
formButton.MouseDown += mouseDownEvent;
formButton.MouseUp += mouseUpEvent;
}
private static void loopTimerEvent(Object source, ElapsedEventArgs e)
{
//this does whatever you want to happen while clicking on the button
}
private static void mouseDownEvent(object sender, MouseEventArgs e)
{
loopTimer.Enabled = true;
}
private static void mouseUpEvent(object sender, MouseEventArgs e)
{
loopTimer.Enabled = false;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)