KeyDown event handler is not working - c#

I am developing an app for Windows 8.1
am using XAML + C#
I read the article this article in MSDN for Responding to keyboard interaction
I did as they say , but the problem is that the event occurs only when i press a key inside a TextBox
but i want the event to occur everywhere i press in the Page
Note: I use a laptop (no touch hardware)
XAML :
<Grid x:Name="GameGrid" Margin="0,0,0,0.111" KeyDown="Grid_KeyDown">
C# :
private void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.A)
this.DoSomething();
}

Try registering an accelerator key instead of a key event on grid (it must have focus to fire the event):
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.acceleratorkeyactivated
Example:
Window.Current.Dispatcher.AcceleratorKeyActivated += ...

Related

How to detect keyboard inputs?

I want to detect when a key on the keyboard is pressed to execute a command. So that when I press the F key it does an action. How I can do it?
You need to process the keyboard events like KeyDown. These provide you with events on every key press or release.
Inside the Event handler you need to filter which key was pressed and execute whatever action needs to be done:
public void MyKeyDownEventHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == 70)
{
MessageBox.Show("'F' key pressed");
}
}
Since the KeyDown event is bound to a control and will only be fired when the control has focus you need to think about from which control you want the event to be fired from. In order to get the event fired from everywhere in your app, this blog post provides a neat solution:
By registering the KeyDown event to all controls during startup of your app, it will always fire as long as your app is in focus since there is always one control in focus. To achieve this, add this to the OnStartup() method of your app (inside the app.xaml.cs):
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Control),
Control.KeyDownEvent,
new KeyEventHandler(MyKeyDownEventHandler));
base.OnStartup(e);
}
}

Button click and virtual keyboard enter key Windows Phone 8

I am developing an app for windows phone. I have a login screen where the user must enter his username and click the LOGIN button in the UI or the enter key in the virtual keyboard of the phone. I capture both the events separately. LOGIN button has a 'Click' event which logs the user in and there is a 'KeyDown' event for the enter key in the virtual keyboard which has the same code as that of the Click event. The events work fine. It logs the user in once the login button or the enter key is pressed. But only when the login button or the enter key is pressed twice. The event gets captured in the first click (I saw the page being refreshed) but only the second click takes the user into the application. Any possible ideas to come out of this issue?
Earlier I did not have the LOGIN button, only used the enter key in virtual keyboard and things were working fine in the first click
Regards
Karthik
Just created simple example that worked fine, try to reproduce it.
Xaml:
<StackPanel Orientation="Horizontal">
<TextBox KeyDown="TextBox_KeyDown"/>
<Button Click="Button_Click" VerticalAlignment="Top"/>
</StackPanel>
Code-behind:
private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter || e.Key == Windows.System.VirtualKey.Accept)
HandleAll();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
HandleAll();
}
private void HandleAll()
{
//Hit breakpoint here
}
"HandleAll" method invoked every-time when Button or Keyboard Enter clicked.
I am not sure whether my approach was wrong. Theoretically if the logic of the HandleAll() method is present in both the Button_click and key_down event, it should give the same result (comparitevely poor performance though). Now I found that the problem is not due to using the same logic in both the events (without the HandleAll()) but because of the creation of new AppSettings in the windows phone. The following solves the issue for me:
private void Login_button_click(object sender, RoutedEventArgs e)
{
//Code
AppSettings settings = new AppSettings();
settings.IsLoggedOutSetting = false;
//Code
}
private void textbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//code
AppSettings settings = new AppSettings();
settings.IsLoggedOutSetting = false;
//code
}
}
With the above code , the issue is solved. So from my observation, the problem was because of not creating a new setting for the App when the user is trying to log in the windows phone app.
But the answer provided above by Vladimir would NOT have led me into this issue at the first place as well as the answer by Vladimir was efficient(space and time).
Thanks to you Vladimir. I was so curious why my earlier logic didn't work and found out the windows app needs a new setting to be setup when a user logs in through either the button_click or key_down events

Capturing Key Press Event in my WPF Application which do not have focus

I have developed an On Screen Keyboard in WPF. I need to capture the key
press event (via Key Board) in order to keep a track of Caps Lock, Shift
etc (whether they are pressed).
Please note that my application loses focus when any other application
(say notepad) is opened.
Could anyone suggest how to achieve this in WPF?
in short, my WPF application needs to capture the key press events even
though it does not have focus. Kindly help.
This was helpful for me : Disable WPF Window Focus
Its not exactly the same as your problem, he is trying to catch an event without getting focus , but its a good starting point
I use a simple code behind:
In the xaml I use a KeyDown event called MyTestKey.
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
KeyDown="myTestKey" >
This is what the keydown routine looks like where I check for the number 1:
private void myTestKey(object sender, KeyEventArgs e)
{
if ((e.Key == Key.D1) || (e.Key == Key.NumPad1))
{
//do some stuff here
return;
}
}
This is an easy way to get to any key. I hope this helps.

WPF windows forms host keyboard events

This is probably a simple question but i've been unable to find a quick answer.
I have a WPF application which has a Windows Forms Control hosting a GeckoFX component (doesn't really matter).
What i want to do is capture key down events inside the Windows Forms Control and grab focus of a WPF control for some particular key combination.
And what if i want to capture events from the entire WPF application window (even inside the Windows Forms Control)?
I tried handling the KeyDown event and PreviewKeyDown event but to no avail.
What i want to know is if this is possible and how this should be done. I can post some code if required.
The KeyDown even on the Form should work for non special keys (like arrow keys). Use PreviewKeyDown to capture those, or use this solution.
For GeckoWebBrowser specifically, I had to use PreviewKeyDown. Also, I added a line so it doesn't break in design mode:
private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (DesignMode) return;
if (!e.IsInputKey && e.Control && e.KeyCode == Keys.S) {
DoStuff();
return;
}
}

Windows Forms: detect the change of the focused control

I'm implementing copy-paste in a Windows Forms application.
I need to enable/disable the bar-buttons for this two operations when the user changes the focused element in the application.
I can find the current focused control using something like this: http://www.syncfusion.com/FAQ/windowsforms/faq_c41c.aspx#q1021q, but how can I detect that the focused control has changed?
In your form load event handler you could also loop through all of the controls contained in the form and for each focusable control add an event handler for the Enter event:
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control control in Controls)
{
control.Enter += ControlReceivedFocus;
}
}
void ControlReceivedFocus(object sender, EventArgs e)
{
Debug.WriteLine(sender + " received focus.");
}
My proposal is to use Application.Idle event.
Write logic that enables/disables your buttons in Application.Idle event.
Subscribe to Application.Idle event on form shown event
Check button availability on button click (so you never pass accidental click under heavy load)
Do not forget to remove Idle handler on form disposing (or closing), because this is static event
Using this technique you will always have correct buttons state, and you not need to worry about subscribing to many controls events to detect focus change. This is also light-weight approach, because Idle event is raised only when application is not busy.
I think you should add an event handler to the control (or if you have many of the same type, subclass it, and override the appropriate OnChange handler). This way you won't have to 'find' the focused control (it will be given as the sender parameter), and the event will only arise when the change actually happened.
To detect the focus on a control you can create this event:
void MyGotFocus(object sender, EventArgs e)
{
if (sender is TextBox)
{
//TODO YOUR OPERATION
//FOR EXAMPLE
(sender as TextBox).SelectAll();
}
}
and the next step is to associate the control and event by code:
myText1.GotFocus += MyGotFocus;
myText2.GotFocus += MyGotFocus;

Categories