简体   繁体   English

按钮上的C#Winform循环事件

[英]C# Winform looping event on Press Button

I made two buttons which controls scrolling on a DataGrid OnClick. 我做了两个按钮,用于控制在DataGrid OnClick上的滚动。 I'll like to execute the code managing the scroll when users stay press on it. 当用户持续按下滚动条时,我想执行管理滚动条的代码。

I tried on MouseDown() but the code is execute only one time. 我试过了MouseDown(),但是代码仅执行一次。

Need help. 需要帮忙。

  • When you get a mouse down event, set a timer to start calling a "scroll" callback function every 200ms or so (random guess on the time). 当发生鼠标按下事件时,请设置一个计时器,以每200毫秒左右(时间随机猜测)开始调用“滚动”回调函数。
  • In the timer callback, scroll by one "notch" (however much you make it.) 在计时器回调中,滚动一个“凹口”(无论您完成多少)。
  • When you get a mouse up event, stop the timer. 当您发生鼠标上移事件时,请停止计时器。

If you don't want to use the timer, you can always spawn a thread when needed. 如果您不想使用计时器,则始终可以在需要时生成线程。 You only have to be careful to use Invoke() mechanism when using the UI controls, which are on the other thread. 使用另一个线程上的UI控件时,只需注意使用Invoke()机制。

Code: 码:

private bool mouseDown = false;

private void buttonScrollUp_MouseDown(object sender, MouseEventArgs e)
{
  mouseDown = true;
  new Thread(() => { 
    while (mouseDown)
    {
      Invoke(new MethodInvoker(() => [DO_THE_SCROLLING_HERE));
      Thread.Sleep([SET_AUTOREPEAT_TIMEOUT_HERE);
    }
  })
  .Start();
}

private void buttonScrollUp_MouseUp(object sender, MouseEventArgs e)
{
  mouseDown = false;
}

Code snippet above of course lacks some sanity and error cheks. 上面的代码片段当然缺乏理智和错误检查。

LP, Dejan LP,德扬

Main idea is to implement timer, for example every 100ms, and do your logic in tick event. 主要思想是实现计时器,例如每100毫秒执行一次,并在滴答事件中执行逻辑。 Algorithm can look like: 算法看起来像:

  1. Capture mouse and start timer in MouseDown event 捕获鼠标并在MouseDown事件中启动计时器
  2. In MouseMove detect is cursor still over button, if no set flag 在MouseMove中,如果没有设置标志,则检测光标仍在按钮上方
  3. In timer tick check flag is mouse over button, and do your scroll logic 在计时器中,勾选标记是将鼠标悬停在按钮上方,并执行滚动逻辑
  4. Release mouse capture and stop timer in MouseUp event 在MouseUp事件中释放鼠标捕获并停止计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM