Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Binding TextBlock with KeyDown event

Back to Forum: Tech Off
  • User profile image
    trun_gup

    i am using textblock for capturing input from keyboard, but problem is how do i refresh its content, i am doing the way given below, but then it doesnot works for space, enter or any other sytemkey, how do i go about it?

    TextBlock tb

    KeyDown event of windows:
     
    tb.Text = tb.Text + e.Key.ToString();

  • User profile image
    defstream

    This should work. Doing it on the KeyDown event however would need more code to format it with correct placing and etc but a minimilized version would be. Also note I am using a TextBox and not a TextBlock?

                TextBox TextBlock = sender as TextBox;
                TextBlock.Text +=  System.Convert.ToChar(e.KeyValue);
                TextBlock.SelectionStart = TextBlock.Text.Length;

    The last line simply moves to caret to the end of the textbox.

  • User profile image
    samjudson

    After a bit of fluffing about I got this code snippet to cover 'most' keys. You'd have to do some bizarre state handling to determine if the shift key is pressed down to convert the alpha to lower or upper I guess, and this doesn't handle special characters (%£"$';,. etc).

                if (e.Key >= Key.A && e.Key <= Key.Z)
                    TextBlock1.Text += e.Key.ToString();
                else if (e.Key >= Key.D0 && e.Key <= Key.D9)
                    TextBlock1.Text += e.Key.ToString().Remove(0, 1);
                else if (e.Key == Key.Space)
                    TextBlock1.Text += " ";
                else if (e.Key == Key.Return)
                    TextBlock1.Text += (char)13;

                e.Handled = true;

  • User profile image
    trun_gup

    i think this works fine.. but how to control shift + key or control + shift combinations..

  • User profile image
    kettch

    I think that KeyEventArgs.Modifiers is what you are looking for.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.