2
votes

I'm trying to build a Universal Windows App (in Visual Studio 2015) using XAML and VB. The task is: A simple TextBlock should display every number typed on the keyboard using the KeyDown Event. The TextBlock is located on a Grid on the MainPage.

I have already tried to use the KeyDown Event of the Grid and the KeyDown Event of the MainPage. Neither of them seems to work (see Code below). The Event is just not triggered wenn pressing a Key down. It worked quite well when typing a text in a TextBox (the TextBlock displaying the currently pressed Key). But thats not what I want.

XAML:

<Page
x:Class="App2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" KeyDown="Page_KeyDown">

<Grid x:Name="frm_main" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock x:Name="txt_Ausgabe" HorizontalAlignment="Left" Margin="704,118,0,210" TextWrapping="Wrap" Text="hgbv,hjghj" VerticalAlignment="Top" Height="752" Width="448" FontSize="72" TextAlignment="Center" FontWeight="Bold"/>
 </Grid>

VB:

Public NotInheritable Class MainPage
Inherits Page

Private Sub Page_KeyDown(sender As Object, e As KeyRoutedEventArgs)
    txt_Ausgabe.Text = e.Key
End Sub

End Class
1
The class you need to implement is the CoreWindow.GetForCurrentThread class and bind the keydown event to it. However, I'm not well versed in how to do that in VB (in c# its as simple as CoreWindow.GetForCurrentThread().KeyDown += Page_KeyDown) - Takarii
Thanks Takarii, that was the hint I'd needed! - Patrick

1 Answers

0
votes

First you have to make an Object of the CoreWindow-Class and then link your main Window to it using the GetForCurrentThread function of the CoreWindow class. This is best done in the Constructor of the MainPage-Class

Public NotInheritable Class MainPage

Inherits Page
Public WithEvents MainWindow As Windows.UI.Core.CoreWindow

    Sub New()
        MainWindow = Windows.UI.Core.CoreWindow.GetForCurrentThread()
    End Sub

End Class

Now the Object contains the KeyDown-Event you need. For example:

Private Sub Page_KeyDown(sender As Windows.UI.Core.CoreWindow, e As Windows.UI.Core.KeyEventArgs) Handles MainWindow.KeyDown