QuarK
QuarK

Reputation: 1312

How to catch mouse button events in another thread

I am a newbie in WinForms and I have question about MouseDown and MouseUp events (sorry, if I duplicate it, but I cann't google it). So, I have a PictureBox and paint cube on it. But I need to rotate it, using the mouse. I use auto-generated events MouseDown, MouseUp, MouseMove. First of them just change bool variable (it's stupid way to check, but I cann't find the better one).

    private void PictureBox_MouseDown(object sender, MouseEventArgs e)
    {
        RMBIsPressed = true;
    }

    private void PictureBox_MouseUp(object sender, MouseEventArgs e)
    {
        RMBIsPressed = false;
    }

In MouseMove I have do {} while(), that checks state of RMBIsPressed and repaint cube, if it's need.

    private void PictureBox_MouseMove(object sender, MouseEventArgs e)
    {
        Point mousePoint = MousePosition;
        Point mousePointNext;
        do
        {
            mousePointNext = MousePosition;
            if (mousePointNext != mousePoint)
            {
                if (mousePoint.X < mousePointNext.X)
                {
                    teta += deltaTeta;
                }
                else
                {
                    teta -= deltaTeta;
                }
                if (mousePoint.Y < mousePointNext.Y)
                {
                    phi += deltaPhi;
                }
                else
                {
                    phi -= deltaPhi;
                }
                PictureBox.Refresh();                    
                ViewTransformation();
                DrawCube();
            }
            mousePoint = MousePosition;
        } while (RMBIsPressed);
    }

When MouseUp event happens first time, everything is all right, but in next iteration RMBIsPressed is still true, even if I release RMB. It seems do while blocks the MouseUp event. My question is: can I create another thread, which will catch MouseUp and MouseDown events and change value of RMBIsPressed? If it's possible, please tell me how.

Upvotes: 0

Views: 616

Answers (2)

Lorek
Lorek

Reputation: 855

At the end of your do {} call Application.DoEvents(). That will process the windows messages in the buffer, which means the mouse up event will get processed. You might also want to capture the mouse in mouse down.

Upvotes: -1

Richard Schneider
Richard Schneider

Reputation: 35477

The do-while loop is not letting events being processed.

  • Rename mousePoint to lastPosition and make it an instance variable.
  • Set lastPosition in MouseDown and at end of MouseMove.
  • Remove do-while in MouseMove

I would also change PictureBox.Refresh to PictureBox.Invalidate. This will avoid flicker when mouse is moving very fast.

Upvotes: 2

Related Questions