Shantanu Gupta
Shantanu Gupta

Reputation: 21098

Catching Keycombination on all windows in WPF without adding event on every window

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

Answers (3)

Tergiver
Tergiver

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

Tony
Tony

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:

http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/aeac920b-a64f-43b3-976b-2f7c91a5212b/wpf-get-all-windows-in-an-application.aspx

http://www.codegain.com/articles/wpf/miscellaneous/how-to-detect-ctrl-alt-key-combinations-in-wpf.aspx

Upvotes: 0

Tony
Tony

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

Related Questions