按下鼠标按下按钮时C#循环 [英] C# loop while mousedown button pressed

查看:86
本文介绍了按下鼠标按下按钮时C#循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按下鼠标左键时使用循环:

I'd like to use loop while left mousebutton is pressed:

  private void Loop_MouseDown(object sender, MouseEventArgs e)
        {
            while (e.Button==MouseButtons.Left)
            {
            //Loop
            }
        }

我无法从该线程使用解决方案:
C#如何在按住鼠标按钮时循环播放 因为我通过RS232数据发送,并且使用具有自己间隔的计时器不起作用.同样,该主题的任何解决方案均不适用于我. 它也不能像这里这样工作:

I can't use solution from this thread:
C# how to loop while mouse button is held down because I'm sending via RS232 data and using timer with it's own interval doesn't work. Also any solution from this topic doesn't work for me. It can't also work one like here:

 if (e.Button == MouseButtons.Left)
    {
        //loop
    }

此解决方案也不起作用:

This solution also doesn't work:

bool isLooping = false;

//on mouse down
private void myControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) {
    isLooping = true;
    runLoop();
}

//on mouse up event
private void myControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) {
    isLooping = false;
}

//This is the main loop you care about.  Put this in your application
//This should go in its own thread
void runLoop() {
    while (isLooping) {
        //do stuff
    }
}

因为调用runLoop会阻塞线程,因此MouseUp事件将永远不会触发.

because calling runLoop would block the thread, and so the MouseUp event would never fire.

那么如何使其正常工作?

So how to make it work correctly?

推荐答案

使用BackGroundWorker.非常适合您的问题.

Use a BackGroundWorker. Perfect for your problem.

将循环功能置于工作程序中,并在发生鼠标事件时启动/停止工作程序.

Put the loop function in the worker and start / stop the worker on mouse events.

这篇关于按下鼠标按下按钮时C#循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆