你能为我指出正确的方向吗?我试图在按下表单按钮时触发循环。

//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;
}

10-05 23:32