【问题标题】:KeyDown Event Universal Windows App in Visual Studio with VB带有 VB 的 Visual Studio 中的 KeyDown 事件通用 Windows 应用程序
【发布时间】:2016-11-21 11:55:14
【问题描述】:

我正在尝试使用 XAML 和 VB 构建通用 Windows 应用程序(在 Visual Studio 2015 中)。任务是:一个简单的 TextBlock 应该显示使用 KeyDown 事件在键盘上键入的每个数字。 TextBlock 位于 MainPage 的 Grid 上。

我已经尝试过使用 Grid 的 KeyDown 事件和 MainPage 的 KeyDown 事件。它们似乎都不起作用(参见下面的代码)。按下一个键就不会触发事件。在 TextBox(显示当前按下的键的 TextBlock)中键入文本时,它工作得很好。但这不是我想要的。

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

【问题讨论】:

  • 你需要实现的类是CoreWindow.GetForCurrentThread类并绑定keydown事件。但是,我并不精通如何在 VB 中做到这一点(在 c# 中就像 CoreWindow.GetForCurrentThread().KeyDown += Page_KeyDown 一样简单)
  • 谢谢 Takarii,这正是我需要的提示!

标签: vb.net xaml keydown


【解决方案1】:

首先,您必须创建一个CoreWindow 类的对象,然后使用CoreWindow 类的GetForCurrentThread 函数将主窗口链接到它。这最好在 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

现在对象包含您需要的 KeyDown-事件。 例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多