Search code examples
c#.nettextboxonkeydown

Detection of Backspace on KeyDown


I am working on a Silverlight web app. It interacts with a module that sends SMS's. I want to limit the text to 160 and show a counter. I did it like this:

public partial class SendSMSView
{
    public SendSMSView()
    {
       InitializeComponent();
       ApplyTheme();
    }

    protected void tbMessage_KeyDown(object sender, KeyEventArgs e)
    {
        count = 160 - this.tbMessage.Text.Length;
        this.lblCount.Content = count.ToString();
    }
}

This works fine for all the keys except backspace and delete. Of course, it is made to function like this. I dug more on this and tried overriding KeyDown event. So, I added the following code snippet:

public class CustomTextBox : TextBox
{
    public CustomTextBox(): base()
    {
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        e.handler=false;
        base.OnKeyDown(e);
        //this place
    }
}

In OnKeyDown function, I get all the keystrokes registered. Setting Handler to false here doesn't help and still I can't get backspace to trigger tbMessage_KeyDow.

I want to somehow call the tbMessage_KeyDow function from //this place forcefully from there for backspace.

I searched MSDN and found that IsInputKey can be overridden to return true so that OnKeyDown responds to it as well, but My framework neither has IsInputKey nor PreviewKeyPress. Is there a workaround for getting backspace key registered as input key, or to call tbMessage_KeyDow [which is very crude approach]? Please help!


Solution

  • try this ....

    If you want to detect the backspace key on the key pressed in a textbox. we would suggest that you can try to do in the textbox's KeyUp event instead of the KeyDown event. for example:

       <TextBox x:Name="txt" KeyDown="txt_KeyDown" Text="Hello" KeyUp="txt_KeyUp"></TextBox>    
    

    the codebehind:

        private void txt_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Back)
            {
                MessageBox.Show(this.txt.Text);
            }
        } 
    

    or you can do like this...by creating a user control....

    public partial class Page : UserControl {
    
        private TextBox TextBox1;
    
        public Page() {
            InitializeComponent();
            TextBox1 = new TextBox();
            Width = 300;
            Height = 100;
            LayoutRoot.Children.Add(textbox);
            OnTextChanged(((object)(sender)), ((TextChangedEventArgs)(e)));
            TextBox1.TextChanged;
            if (e.Key == Key.Back) {
                e.Handled = true;
            }
            else if (e.Key == Key.Delete) {
                e.Handled = true;
            }
        }
    }