The UWP (Universal Windows Platform) for modern app development on the Windows platform requires various input methods and validations. In this course, we will take a closer look at how to handle basic input in UWP applications.
Understanding the UWP Input System
UWP applications support various input devices, including mouse, keyboard, touch, and game controllers. These input technologies allow you to design interactions with users. UWP apps can respond to specific events and methods for each input source.
Basic Input Handling
UWP provides various events for basic input events. To handle input in our app, we need to receive those events, analyze the user’s input, and respond appropriately.
1. Mouse Input
Mouse input is one of the most basic input methods in UWP apps. Mouse clicks can be handled using the PointerPressed
and PointerReleased
events.
Example: Handling Mouse Click Events
<Grid x:Name="MyGrid" PointerPressed="MyGrid_PointerPressed">
<TextBlock x:Name="OutputTextBlock" Text="Please click!" />
</Grid>
// C# code
private void MyGrid_PointerPressed(object sender, PointerRoutedEventArgs e)
{
OutputTextBlock.Text = "You clicked the grid!";
}
2. Keyboard Input
Keyboard input can be handled through the KeyDown
and KeyUp
events. You can detect the keys pressed by the user and perform appropriate actions.
Example: Handling Keyboard Input
<TextBox x:Name="InputTextBox" KeyDown="InputTextBox_KeyDown" />
// C# code
private void InputTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
OutputTextBlock.Text = "Enter key was pressed!";
}
}
3. Touch Input
UWP natively supports touch input, and touch events can be handled similarly to mouse events. The Touch.FrameReported
event is used to manage touch input.
Example: Handling Touch Input
<Grid x:Name="MyTouchGrid" Touch.FrameReported="MyTouchGrid_TouchFrameReported">
<TextBlock x:Name="TouchOutputTextBlock" Text="Please touch!" />
</Grid>
// C# code
private void MyTouchGrid_TouchFrameReported(object sender, TouchFrameEventArgs e)
{
TouchPoints = e.GetTouchPoints(MyTouchGrid);
TouchOutputTextBlock.Text = "Touched!";
}
4. Game Controller Input
UWP supports input from game controllers, such as the Xbox controller. You can handle input using the Gamepad
class.
Example: Handling Gamepad Input
// C# code
var gamepad = Gamepad.Gamepads.FirstOrDefault();
if (gamepad != null)
{
var state = gamepad.GetCurrentReading();
if (state.Buttons.HasFlag(GamepadButtons.A))
{
OutputTextBlock.Text = "A button was pressed!";
}
}
Check the Results
Try applying the basic input handling methods described above to your UWP application. Check the reactions between various input methods and ensure that the user interface is designed to be user-centered.