Dot NET
Dot NET

Reputation: 4907

Unusual dragging issue in C# WinForm

I've got a PictureBox which can be dragged by the user. When the dragging is done, the component appears to move continuously from side to side, like vibrating.

Upvotes: 1

Views: 165

Answers (1)

Yogu
Yogu

Reputation: 9455

Your code is not very logical. It says: If the user drags the note one pixel downwards, the note is set one step down. If the mouse then is moved sidewards, the note moves down a step for every pixel the mouse is moved.

I'd suggest to go back to concept.

  • At first, the mouse distance has to be determined: delta = e.Y - currentY.
  • Then, snap it into the grid: gridDelta = delta / step * step, where step is 10 in your case.

    delta / step represents the number of tones the note is moved. Because we're using Integers, this value is rounded and we only have whole tones. If the mouse is moved 10 (= step) pixels upward, the the next higher tone is chosen.

    delta / step * step is needed because the distance from one tone to the other is 10, i.e. the note should appear 10 pixels above its original position if it's moved one tone higher.

  • Next, add gridDelta to this.Top and check if the result is within the range.
  • Finally, save the value into this.Top.

Maybe numbers make it clearer: If the user presses the mouse button at position Y=14, then drags it up to 48, and then releases, the following happens in the last call of OnDrag:

  • delta = 48 - 14 - delta is 34.
  • gridDelta = 34 / 10 * 10 - 34/10 = 3; 3 * 10 * 30 - so gridDelta is 30.
  • newTop = this.Top + 30
  • Check whether newTop is within the range, and then assign it to this.Top.

You see, the note then is exactly 30 pixels above its original position, although the user dragged it for 34 pixels.

Repetitions like the ones in your code often lead to errors and it's hard to adjust them, so always look for a better algorithm.

Upvotes: 2

Related Questions