views:

126

answers:

2

Using c# in 2008 Express. I have a textbox containing a path. I append a "\" at the end on Leave Event. If the user presses 'Escape' key I want the old contents to be restored. When I type over all the text and press 'Escape' I hear a thump and the old text isn't restored. Here 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,

+3  A: 

Your txtPath_CheckKeys function assigns the path to the old path, but never actually 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;
    }
}
R. Bemrose
+1 Of Course! =P I was searching a bit too far, I guess! Hehehe...
Will Marcouiller
@Will Marcouiller: I've been burned by the obvious things way too often... I tend to look for those first now.
R. Bemrose
Thanks Will!! you're a genius. That was it. I thought the thump was the keystroke getting lost. This if statement "(kpe.KeyChar == (char)27)" was the only way I could do it. Intellisense didn't give me the option of kpe.KeyCode. I'm running VS2008 Express.Thanks again,
+1  A: 

The Control.Validating event might help you.

It describes the order in which events are triggered. So, choosing the event that best suits your need will make it easier to implement this feature.

It might be too much for the need, but trying to Invalidate the control might help too.

Let me know whether it helps.

Will Marcouiller
Good point... the LostFocus event doesn't always fire when a button is activated via the keyboard, but the Validating event does.
R. Bemrose