Reputation: 137
In a UWP application I need input from the Gamepad. It works fine, but I also get the unwanted side effect that the current caret moves through the app as the user moves the thumbstick. How to prevent the caret from moving?
The app is mainly based on MVVM with MVVM light, but the Gamepad is handled in the code behind of the view.
Here is the view constructor in the code behind (the view is called Settings
and derived from Page
).
public Settings()
{
InitializeComponent();
// Gamecontroller
gameControllerUpdateTimer = new DispatcherTimer();
gameControllerUpdateTimer.Tick += gameControllerUpdateTimer_Callback;
gameControllerUpdateTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
GameControllerConnected = false;
Gamepad.GamepadAdded += Gamepad_GamepadAdded;
Gamepad.GamepadRemoved += Gamepad_GamepadRemoved;
}
and the three event handlers: two for Gamepad detection and removal, and one for reading the Gamepad inputs.
// Called periodically to check for user input throught the gamepad
void gameControllerUpdateTimer_Callback(object sender, object e)
{
if (GameControllerConnected)
{
Gamepad gamePad = Gamepad.Gamepads[0];
GamepadReading readings = gamePad.GetCurrentReading();
LeftThumbStickX = readings.LeftThumbstickX;
LeftThumbStickY = readings.LeftThumbstickY;
}
}
// Called upon gamepad detection
async void Gamepad_GamepadAdded(object sender, Gamepad e)
{
await Dispatcher.RunAsync(
CoreDispatcherPriority.Normal, () =>
{
GameControllerConnected = true;
gameControllerUpdateTimer.Start();
});
}
// Called upon gamepad removal
async void Gamepad_GamepadRemoved(object sender, Gamepad e)
{
await Dispatcher.RunAsync(
CoreDispatcherPriority.Normal, () =>
{
GameControllerConnected = false;
gameControllerUpdateTimer.Stop();
});
}
EDIT: Below there's a screenshot of the app I'm working on. The caret/cursor is in one of the Textbox
. When I move the left thumbstick on the Gamepad
, the caret/cursor moves too: it moves from one Textbox
to the other, or maybe better saying it causes the app to change the currently focused UI Control.
Upvotes: 1
Views: 465
Reputation: 325
Why don't you use the KeyDown
event on the top UIElement
in your view?
private void Grid_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
if(e.Key == Windows.System.VirtualKey.GamepadLeftThumbstickLeft ||
e.Key == Windows.System.VirtualKey.GamepadLeftThumbstickRight ||
e.Key == Windows.System.VirtualKey.GamepadLeftThumbstickDown ||
e.Key == Windows.System.VirtualKey.GamepadLeftThumbstickUp)
{
// do something or... nothing
e.Handled == true;
}
}
Upvotes: 2