按住鼠标按钮时C#如何循环

Sin*_*tic 14 c# events mouseevent

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

//pseudocode
While (button1 is pressed)
value1 += 1
Run Code Online (Sandbox Code Playgroud)

当然,当释放按钮时停止循环

Dog*_*ett 27

为了避免使用线程,你可以添加一个计时器上的表单/控制组件,并简单地使其在按下鼠标和禁用它的鼠标了.然后将通常放在循环中的代码放入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;
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*mwi 11

您可以使用线程进行计数,并在释放鼠标时停止线程.以下对我有用:

var b = new Button { Text = "Press me" };

int counter = 0;
Thread countThread = null;
bool stop = false;

b.MouseDown += (s, e) =>
{
    stop = false;
    counter = 0;
    countThread = new Thread(() =>
    {
        while (!stop)
        {
            counter++;
            Thread.Sleep(100);
        }
    });
    countThread.Start();
};

b.MouseUp += (s, e) =>
{
    stop = true;
    countThread.Join();
    MessageBox.Show(counter.ToString());
};
Run Code Online (Sandbox Code Playgroud)

当然,如果您希望事件处理程序是方法而不是lambdas,则必须将所有变量都转换为字段.


小智 8

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        timer1.Enabled = true;
        timer1.Start();

    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        timer1.Stop();
    }



    private void timer1_Tick(object sender, EventArgs e)
    {
        numericUpDown1.Value++;

    }
Run Code Online (Sandbox Code Playgroud)