Reputation: 21098
I want to add a KeyPress event on Application level which checks certain key combination whenever it is pressed.
If keycombination is matched. I want to open a window on the current window that is executing.
How can I do this.
Edit
I want to add KeyPress event on Application class so that it can capture key pressed on all the windows. One way to do is, I can go to every Window and add event on each window. But what if number of windows is large enough. this is what my scenario is.
So I was trying to do something on Application class to do the same work.
How can I do
Upvotes: 3
Views: 2794
Reputation: 14517
Use the PreviewKeyDown
event. This is sent by each control before they process the key themselves.
As an alternative, you can use CommandBindings.
Upvotes: 1
Reputation: 17657
As a clean and simple solution, maybe you could use something like this: Instead of you manually add the event on every window, you make the computer do it for you.
private void AssignEventHandlers()
{
foreach (Window window in Application.Current.Windows)
{
//if (window != Application.Current.MainWindow)
window.KeyDown += new System.Windows.Input.KeyEventHandler(window_KeyDown);
}
}
void window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
// MessageBox.Show(e.Key.ToString());
if (System.Windows.Input.Keyboard.Modifiers == (System.Windows.Input.ModifierKeys.Control | System.Windows.Input.ModifierKeys.Alt)
&& e.Key == System.Windows.Input.Key.O)
{
MessageBox.Show(System.Windows.Input.Keyboard.Modifiers.ToString() + " " + e.Key.ToString());
}
}
Sources:
Upvotes: 0
Reputation: 17657
Maybe you can try to use Low-level Windows API hooks from C# something like this: http://www.codeproject.com/KB/system/CSLLKeyboard.aspx
this will involve code using System.Runtime.InteropServices and user32.dll
...
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
// and the code to create the event handler, etc... See more on the referred article.
...
Upvotes: 0