WPF windows forms host keyboard events - c#

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;
}
}

Related

KeyDown event handler is not working

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 += ...

Best way to show/hide .NET application using a keyboard shortcut? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Global keyboard capture in C# application
Hi all,
I am making a .NET application (Window Forms) which is written by C# and I get a problem. How to hide my personal .NET application using a keyboard shortcut and then displaying it back from same keyboard shortcut.
Thanks !
First you should probably clarify which technology you're using: WinForms, WPF?
Anyway, using WinForms You can use the KeyDown event to process such occurrences:
private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.Shift && e.KeyCode == Keys.M)
{
WindowState = FormWindowState.Minimized;
}
}
Note that the modifier key/s and regular key/s you require to be pressed to carry out the action are obviously changeable.
A further note is that once this action has been executed then the window no longer has 'focus' and so repeating the keystrokes to display the window again will not work - for this to happen you will need to register a hot-key that Windows itself knows about or use a keyboard hook to intercept keystroke input to the system to consume in your application, AFAIK.

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.

Handle clipboard copy on UserControl

I have complex UserControl (grid, edit controls for grid, etc...) and I want handle CTRL+C keyboard shortcut, however I don't want disable a native functions by edit controls (textboxes, comboboxes, etc...). If the CTRL+C is not handled by other inner controls I want handle it by myself (copy whole row(s) from grid, etc...).
I tried override WndProc method in UserControl and check for WM_COPY and WM_COPYDATA, but it doesn't work. It works only on final target control (TextBox for example).
You can do this by overriding ProcessCmdKey(). Check if a text box has the focus. For example:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.C)) {
var box = this.ActiveControl as TextBoxBase;
if (box == null) {
// Do your stuff
MessageBox.Show("Copy!");
return true;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
What you are looking for is a way to bubble events raised by a child control up to its container so that you can handle those events at the User Control's level.
The automatic propagation of events across the control hierarchy is built into WPF and is called Routed Events. However this functionality is not available out of the box in Windows Forms, so you will have to implement your own solution.
Have a look at this SO question to get some inspiration.
Related resources:
How to route events in a Windows Forms application
I didn't try it out and i think it heavy depends on all the child controls, which are within your UserControl. But normally a keystroke is given to the actual control that has the focus. If it doesn't handle that keystroke (setting e.Handled = true), it would be bubble up to its parent and if that doesn't handle it, it would go further till it reaches the form and finally the limbus.
So if your child controls are properly written and they can't handle the given keystroke (e.g. Control + C) it should be easy to add a handler into your UserControl to the KeyDown event and do whatever you like.
Update
After reading your comments, i still think that the way shown by Enrico and me should be the correct one. So i think the problem is that if one of your 3rd party controls has the focus it is not able to handle the copy shortcut, but it sets the e.Handled = true leading to no further informations of the parent controls about the shortcut.
So at first you should contact your control vendor and send him a bug report about this wrong behaviour.
Alternative there exists another hacky way:
In your form you can set the KeyPreview to true and intercept the incoming key. Now you could check if within the ActiveControl is something that handles the shortcut correctly (maybe a check against a Dictionary<Type, bool> or a HashSet<Type> lackingControls) and just leave the function or do whatever you want and setting the e.Handled = true by yourself.
Update 2
A little snippet to illustrate what i meant:
this.KeyPreview = true;
HashSet<Type> scrappyControls = new HashSet<Type>();
//ToDo: Add all controls that say it handles Ctrl-C
// but doesn't it the right way.
scrappyControls.Add(typeof(TextBox));
this.KeyDown += (sender, e) =>
{
if (e.KeyData == (Keys.Control | Keys.C))
{
if (scrappyControls.Contains(this.ActiveControl.GetType()))
{
//ToDo: Do copy to clipboard on yourself
e.Handled = true;
}
}
};
The drawback of this functionality is, that it must be placed into your form, not into your self-written UserControl. But that way you will be informed, when a TextBox has the focus and Control + C is pressed within.

Winform keyboard management

I would like to control the focus of my winform application. It is made of a custom listbox and several other component.
I want all the keyboard event be managed by my window handlers in order to avoid specific control key handling (for example when I press a character and the list box is focused, the item starting with the correspondant letter is selected which is not a correct behaviour for my application).
How can I achieve this?
Make sure your form's KeyPreview property is set to true. Then this code should work for canceling your key events to the listbox...
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.ActiveControl == listBox1)
e.Handled = true;
}
The KeyPress event may not work for all your scenarios. In that case, I would try out the KeyDown event.

Categories