Gasta87
Gasta87

Reputation: 225

Catch a mouseUP event during a while

here is my code:

public partial class Form1 : Form
{
    Graphics g;
    bool mouseUP = false;
    double dimensions = 4.0;
    SolidBrush brush;

    public Form1()
    {
        InitializeComponent();
        g = this.CreateGraphics();
        brush = new SolidBrush(Color.Black);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        mouseUP = false;
        backgroundWorker1.RunWorkerAsync(e);
    }

    private bool mouseIsUP()
    {
        return mouseUP;
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        mouseUP = true;
        MessageBox.Show("UP");
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundWorker1.ReportProgress(0,e.Argument);  
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        while (!mouseIsUP())
        {
            g.FillEllipse(brush, ((MouseEventArgs)e.UserState).X - (int)dimensions / 2, ((MouseEventArgs)e.UserState).Y - (int)dimensions / 2, (int)dimensions, (int)dimensions);
            dimensions += 0.2;
            Thread.Sleep(10);
        }
    }
}

Why the event mouseUP is never occurring??? If i remove the while I can see the MessageBox "UP"...

I'm trying to make bigger a ellipse while the mouse is pressed. When I release the mouse button the ellipse should not grow more.

Thanks in advance!

Upvotes: 0

Views: 913

Answers (2)

M.S.
M.S.

Reputation: 71

It looks like the background worker is somehow blocking the event loop in your code. Where is DoWork being called on the worker?

I think a better solution might be to override the OnPaint method, check if the mouse is down there, then draw your circle.

bool isMouseDown = false;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    isMouseDown = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    isMouseDown = false;
}
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    if (isMouseDown)
    {
        g.FillEllipse(brush, ((MouseEventArgs)e.UserState).X - (int)dimensions / 2, ((MouseEventArgs)e.UserState).Y - (int)dimensions / 2, (int)dimensions, (int)dimensions);
        dimensions += 0.2;
        Thread.Sleep(10);

    }
}

Upvotes: 1

David Arno
David Arno

Reputation: 43254

Because you are not binding your event handlers to the events (assuming you didn't just miss out that code).

For example, within Form1's constructor, you could add

MouseUp += Form1_MouseUp;
MouseDown += Form1_MouseDown;

Upvotes: 1

Related Questions