简体   繁体   中英

Always increasing size of rectangle with mouse down event?

How do I always increasing size of rectangle with mouse down event?

private void btnPlus_MouseDown(object sender, MouseEventArgs e)
{
    rect.Width = rect.Width + 1;
    rect.Height = (int)(((rect.Width) / 4) * 3);

    label1.Text = rect.Width.ToString();
    label2.Text = rect.Height.ToString();

    pictureBox1.Invalidate();
}
  1. On mouse down you start timer
  2. On timer tick you run your code.
  3. On mouse up you stop timer.

The MouseDown event is being called only once when you click the mouse button, even if you keep your finger on the button.

If you want to keep doing a task while your finger is down on the button, create a new thread in the MouseDown event and kill it in the MouseUp event. In the thread, perform a while loop where you perform the increase:

private Thread _increaseWidthThread;
private Boolean _endThreadFlag;

private void btnPlus_MouseDown(object sender, MouseEventArgs e)
{
    _endThreadFlag = false;
    increaseWidthThread = new Thread(() => IncreaseWidth);
}

private void btnPlus_MouseDown(object sender, MouseEventArgs e)
{
    _endThreadFlag = true;
}

private void IncreaseWidth() {
    while (!_endThreadFlag) {
        this.Invoke((MethodInvoker) delegate {
            rect.Width = rect.Width + 1;
            rect.Height = (int)(((rect.Width) / 4) * 3);

            label1.Text = rect.Width.ToString();
            label2.Text = rect.Height.ToString();

            pictureBox1.Invalidate();
        });
    }
}

I use a flag to indicate to the thread when it should stop and an anonymous method to update the GUI from the thread.


EDIT

Instead of using a thread, it is maybe better (and simpler) to use a timer as suggested by Andrey . You will be able to adjust the "sensitivity" of the increase by setting the timer interval.

Assuming you use winforms, that would look like:

private System.Windows.Forms.Timer _timer; 

public ClassConstructor () {
    _timer = new System.Windows.Forms.Timer();
    _timer.Interval = 100;  // Set the "sensitivity"
    _timer.Elapsed += new ElapsedEventHandler(OnTimer);
}

private void btnPlus_MouseDown(object sender, MouseEventArgs e)
{
    timer.Start();
}

private void btnPlus_MouseDown(object sender, MouseEventArgs e)
{
    timer.Stop();
}

private void OnTimer(object sender, ElapsedEventArgs e) {
    rect.Width = rect.Width + 1;
    rect.Height = (int)(((rect.Width) / 4) * 3);

    label1.Text = rect.Width.ToString();
    label2.Text = rect.Height.ToString();

    pictureBox1.Invalidate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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