-1

I decided to create a login form and use the Form.AcceptButton property for the first time. I have a problem with locking controls while my Login function is running.

  • When I hit enter to login, the form freezes before the cursor changed to the WaitCursor and the controls are locked.

  • When I click the login button, the form freezes after the cursor changes to the WaitCursor and the controls are locked (preferred behavior).

Here is my code (simplified):

private void btnLogin_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;

    // foreach loop that sets Enabled = false on all controls on form
    LockControls(); 

    // this function tries to login to SOAP web service, sometimes it takes few seconds
    Login();

    this.Cursor = Cursors.Default;

    // foreach loop that sets Enabled = true on all controls on form
    UnlockControls(); 
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Kamil
  • 13,363
  • 24
  • 88
  • 183
  • @Hans That is one of my favourite question – Sriram Sakthivel Sep 09 '13 at 15:59
  • This is not duplicate, and `this.UseWaitCursor` didn't helped. Please read part about locking controls before you mark this as duplicate. – Kamil Sep 09 '13 at 16:01
  • @GrantWinney There is no code that handles `Enter` key press. Looks like "AcceptButton" property of form does it for me and handles it. Please read this: http://msdn.microsoft.com/en-US/library/system.windows.forms.form.acceptbutton.aspx – Kamil Sep 09 '13 at 16:17

2 Answers2

1

What version of .Net Framework and Windows are you working. I tested the following code and the two cases were the same as exactly as what you prefer:

private void btnLogin_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;

    foreach (var c in this.Controls.OfType<Control>())
       c.Enabled = false;

    Thread.Sleep(5 * 1000);

    Cursor = Cursors.Default;

    foreach (var c in this.Controls.OfType<Control>())
       c.Enabled = true;
}
Alireza
  • 10,237
  • 6
  • 43
  • 59
1

On my Win7, VS2012 this also works:

    private void button1_Click(object sender, EventArgs e)
    {
        this.Cursor = Cursors.WaitCursor;

        LockControls(true);

        Login();

        this.Cursor = Cursors.Default;

        LockControls(false);
    }
    private void LockControls(bool mylock)
    {
        this.Enabled = !mylock;
    }
    private void Login()
    {
        Thread.Sleep(5 * 1000);     
    }

The wait cursor appears while the controls are disabled when either the button is clicked or the enter key is pressed.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22