0

I am developing a small game where there are ellipses as targets and textblock over those ellipses displaying an Alphabet(changes every 3 sec).

I want to implement a functionality where a user presses an alphabet on keyboard and if that matches with the alphabet displayed on a certain textblock, a storyboard(animation)named "t1_hit" shall begin.

I tried the following but it isn't working.

XAML(only the textblock part):

<TextBlock x:Name="txbTarget1" Height="26" Canvas.Left="571" TextWrapping="Wrap" Canvas.Top="92" Width="23" FontWeight="Bold" FontSize="16" Foreground="#FF6BE824" RenderTransformOrigin="0.5,0.5" KeyDown="txbTarget1_KeyDown" ><TextBlock.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </TextBlock.RenderTransform><Run Language="en-in"/></TextBlock>

C#:

 string k = "";

        private void txbTarget1_KeyDown(object sender, KeyEventArgs e)
        {
            k = txbTarget1.Text;
            KeyConverter x = new KeyConverter();
            Key kinput = (Key)x.ConvertFromString(k);
            if (e.Key == kinput)
            {
                Storyboard h1 = this.FindResource("t1_Hit") as Storyboard;
                h1.Begin();
            }
        }

Any help is appreciated. Thank you

sketch_TF2
  • 61
  • 1
  • 9

1 Answers1

2

TextBlock cannot get focus, therefore it cannot catch keyboard input.

you have to use element, in which is the focus. E.g window, or usercontrol:

    public void Window_KeyDown(object sender, KeyEventArgs e)
    {
        k = txbTarget1.Text;
        KeyConverter x = new KeyConverter();
        Key kinput = (Key)x.ConvertFromString(k);
        if (e.Key == kinput)
        {
            Storyboard h1 = this.FindResource("t1_Hit") as Storyboard;
            h1.Begin();
        }
    }

From MSDN:

UIElement.KeyDown

Event Occurs when a key is pressed while focus is on this element.

https://msdn.microsoft.com/en-us/library/system.windows.uielement.keydown%28v=vs.110%29.aspx

Gusdor
  • 14,001
  • 2
  • 52
  • 64
Liero
  • 25,216
  • 29
  • 151
  • 297
  • so any suggestions on hw should I implement such functionality? I can't use textbox instead of textblock ... it will ruin the purpose of the game! – sketch_TF2 Sep 17 '15 at 14:35