当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Stop TextChanged event from firing Leave event

问题描述:

I'm working on a simple WinForms application for a public school where users can identify themselves by entering either their network IDs (which are not protected information) or their system IDs (which are protected information). I want to switch to a password character when the program detects a system ID (which is working just fine); however, when I do this, my application also fires the textbox's Leave event, which tells users to fix a problem with the login data...before there's even a problem.

Here's my code:

void login_TextChanged(object sender, EventArgs e)

{

login.UseSystemPasswordChar = login.Text.StartsWith(<prefix-goes-here>);

}

private void login_Leave(object sender, EventArgs e)

{

if (login.Text.StartsWith(<prefix-goes-here>) && login.Text.Length != 9)

{

signInError.SetError(login, "Your System ID must be nine digits.");

login.BackColor = Color.LightPink;

}

else if (login.Text.IsNullOrWhiteSpace())

{

signInError.SetError(login, "Please enter your username or System ID.");

login.BackColor = Color.LightPink;

}

else

{

signInError.SetError(login, string.Empty);

login.BackColor = Color.White;

}

}

Ultimately, I don't know that this will cause a ton of problems, and I could move this validation step to the Click event of the sign in button on my form, but I'd rather do validation piece-by-piece if possible.

网友答案:

Putting the TextBox inside a GroupBox does reproduce that behavior-- which is odd.

If you want to keep your GroupBox, here is a work around:

private void login_TextChanged(object sender, EventArgs e)
{
  login.Leave -= login_Leave;
  login.UseSystemPasswordChar = login.Text.StartsWith(<prefix-goes-here>);
  login.Leave += login_Leave;
}
网友答案:

For whatever reason, the Leave event fires when the login TextBox is inside a GroupBox control. Replacing the GroupBox with a simple Label control prevented the code within the TextChanged event from firing the Leave event.

网友答案:

Yes, this is a quirk of the UseSystemPasswordChar property. It is a property that must be specified when the native edit control is created (ES_PASSWORD). Changing it requires Winforms to destroy that native control and recreate it. That has side-effects, one of them is that the focus can't stay on the textbox since the window disappears. Windows fires the WM_KILLFOCUS notificaiton.

Being inside a GroupBox is indeed a necessary ingredient, Winforms doesn't suppress the Leave event when it gets the notification. Bug.

Many possible fixes. You could set a flag that the Leave event handler can check to know that it was caused by changing the property.

分享给朋友:
您可能感兴趣的文章:
随机阅读: