tags:

views:

180

answers:

4

I need my WPF application to gain focus whenever the user press "window key + s".

My solution was to hook to the keyboard event with SetWindowsHookEx. however the handle I get in return is always 0. when I call to GetLastWin32Error the value is also 0 (i.e. so it actually reports that the previous operation succeeded)

_hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookFunction, _hinstance, 0);
if (_hookHandle == IntPtr.Zero)
 throw new Win32Exception(Marshal.GetLastWin32Error()); 

(It goes without saying that _hinstance has a valid value and so does _hookFunction)

Any Ideas? other solutions?

Thanks.

A: 

Try using this to get the HINSTANCE:

Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
BFree
This is the exact code I'm using, and it returns a valid value.
Eden
A: 

If you only need is to handle specific key combination then it is better to use hotkeys. This shows how setup hotkeys: Hotkeys

Giorgi
And this shows how to hook WndProc in WPF: http://blogs.msdn.com/nickkramer/archive/2006/03/18/554235.aspx
Giorgi
Unless I'm missing something, hooking into WndProc can only intercept message while my window is active. my all point is to gain focus while the user is working in another window? did I got it wrong?
Eden
In winforms WndProc intercepts massages all the time. I am sure it works in the same way in WPF.
Giorgi
But how do you make it intercepts messages that are not directed to your application?? That's the idea behind hooking...
Eden
Did you have a look at the links I posted?
Giorgi
A: 

Here is a good artical on low level keyboard hook in C#. This might have a couple of things you are missing.

SwDevMan81
A: 

I used this hokey code for my app to not only bring focus to the app with a hotkey, but also to launch the app with a hotkey. So just like you press Win+E to launch Windows Explorer, you could press Win+S to launch your applicaiton. Very useful.

http://code.google.com/p/blinkln/source/browse/trunk/HotKey.cs?r=12

Brent