SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

April 28, 2008

Updating the GUI Before a Method Completes

As a Web developer whose formal programming training focused only on console applications and simple GUI apps, it was not immediately obvious to me how to update a (Windows Forms) GUI while a method was still running. Once I decided it was worth the effort to learn how to do so, I was not surprised to find that it is rather easy, using BeginInvoke().

Problem: I have a long-running method and want to update the mouse cursor asynchronously. More accurately, I need to span a couple of methods. There is an image in a PictureBox from which the user needs to select a slice, and the user wants to be able to move the selection window around the image without redrawing the box ("redrawing" is of course from the user's perspective; from the programmer's perspective, the box is redrawn each time it is moved). I want to use this.Cursor = Cursors.Hand in the MouseDown event, leave it in this state during the MouseMove event, and restore the cursor to Cursors.Default in the MouseUp event.

Solution: Create a delegate method, i.e. public delegate void InvokeDelegate();. Create a couple of functions that handle the cursor change:

/// <summary>
/// Changes the cursor to a hand
/// </summary>
private void cursorMove()
{
     this.Cursor = Cursors.Hand;
}

/// <summary>
/// Changes the cursor back to the default
/// </summary>
private void cursorDefault()
{
     this.Cursor = Cursors.Default;
}

Finally, path these method names into InvokeDelegate whilst using BeginInvoke(Delegate method):

private void pbxMain_MouseDown(object sender, MouseEventArgs e)
{
     …
     this.BeginInvoke(new InvokeDelegate(cursorMove));
     …
}

private void pbxMain_MouseUp(object sender, MouseEventArgs e)
{
     …
     this.BeginInvoke(new InvokeDelegate(cursorDefault));
     …
}

TrackBack

Comments

Post a comment

Remember personal info?




deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there