C # winforms events restore textbox content on escape
Using C # in 2008 Express. I have a textbox containing a path. I add "\" at the end to "Remaining Event". If the user hits the Escape key, I want the old content to be restored. When I type text and press Escape, I hear a beat and the old text is not restored. Here's what I have so far ...
public string _path;
public string _oldPath;
this.txtPath.KeyPress += new System.Windows.Forms.KeyPressEventHandler(txtPath_CheckKeys);
this.txtPath.Enter +=new EventHandler(txtPath_Enter);
this.txtPath.LostFocus += new EventHandler(txtPath_LostFocus);
public void txtPath_CheckKeys(object sender, KeyPressEventArgs kpe)
{ if (kpe.KeyChar == (char)27)
{
_path = _oldPath;
}
}
public void txtPath_Enter(object sender, EventArgs e)
{
//AppendSlash(sender, e);
_oldPath = _path;
}
void txtPath_LostFocus(object sender, EventArgs e)
{
//throw new NotImplementedException();
AppendSlash(sender, e);
}
public void AppendSlash(object sender, EventArgs e)
{
//add a slash to the end of the txtPath string on ANY change except a restore
this.txtPath.Text += @"\";
}
Thanks in advance,
a source to share
The txtPath_CheckKeys function assigns the path to the old path, but never updates the text in the TextBox. I suggest changing it to this:
public void txtPath_CheckKeys(object sender, KeyPressEventArgs kpe)
{
if (kpe.KeyCode == Keys.Escape)
{
_path = _oldPath;
this.txtPath.Text = _path;
}
}
a source to share
The event Control.Validating
can help you.
It describes the order in which events are fired. Thus, choosing the event that best suits your needs will make it easier to implement this feature.
It might be too much to be needed, but the Invalidate
control might help as well when trying .
Let me know if this helps.
a source to share