C#如何在按住鼠标按钮时循环 [英] C# how to loop while mouse button is held down

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

问题描述

你能指出我正确的方向吗?我正在尝试在窗体按钮被按下时触发一个循环。

  //伪代码
按(button1)
value1 + = 1

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

解决方案

为避免使用线程,您可以添加计时器组件在您的窗体/控件上,只需启动鼠标,并将其禁用。然后把你通常放在循环中的代码放在Timer_Tick事件中。如果要使用System.Timers.Timer,可以改用Timer.Elapsed事件。



示例(使用System.Timers.Timer):

  Timer = System.Timers.Timer; 
使用Systems.Timers;
使用System.Windows.Forms; // WinForms示例
private static Timer loopTimer;
private Button formButton;
public YourForm()
{
//循环定时器
loopTimer = new Timer();
loopTimer.Interval = 500; / interval(以毫秒为单位)
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)
{
//做任何你想要发生的事情,点击按钮
}
private static void mouseDownEvent(object sender,MouseEventArgs e)
{
loopTimer.Enabled = true;
}
private static void mouseUpEvent(object sender,MouseEventArgs e)
{
loopTimer.Enabled = false;
}


Can you point me in the right direction? I'm trying to get a loop to trigger while the form button is depressed.

//pseudocode
While (button1 is pressed)
value1 += 1

And then of course stop looping when the button is released

解决方案

To avoid using threads you can add a Timer component on your form/control and simply enable it on mouse down and disable it on mouse up. Then put the code you would normally put inside the loop in the Timer_Tick event. If you want to use System.Timers.Timer you can use the Timer.Elapsed event instead.

Example (using System.Timers.Timer):

using Timer = System.Timers.Timer;
using Systems.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)
{
    //do 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;
}       

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

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