Haxxius
Haxxius

Reputation:

C# Winform looping event on Press Button

I made two buttons which controls scrolling on a 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.

Need help.

Upvotes: 0

Views: 1253

Answers (3)

Dejan Stanič
Dejan Stanič

Reputation: 797

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.

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

Upvotes: 1

arbiter
arbiter

Reputation: 9575

Main idea is to implement timer, for example every 100ms, and do your logic in tick event. Algorithm can look like:

  1. Capture mouse and start timer in MouseDown event
  2. In MouseMove detect is cursor still over button, if no set flag
  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

Upvotes: 0

Sam Harwell
Sam Harwell

Reputation: 99869

  • 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).
  • In the timer callback, scroll by one "notch" (however much you make it.)
  • When you get a mouse up event, stop the timer.

Upvotes: 4

Related Questions