Saturday, September 12, 2009

C# / WPF project: "Spotify Friends" Part 1

Let's kick it off with a mixture of C# with WPF and (kind of) C++.
I'll start by saying; this project is in no way associated with or endorsed by the amazingly great music service Spotify. This project has no intent of misusing the Spotify trademark or in any other way step on anyones toes. "Spotify Friends" is just an internal code-name.

Overview


"Spotify Friends" is a [client(s) --> server] project that lets users see what their friends are listening to at the moment. The client also adds the functionallity of controlling the playback with global hot-keys; changing the song or volume while playing games or surfing - without opening the Spotify window.


Part 1. Global keyboard hooking in C# Forms and WPF


How it's done in C++


If we were to make a Windows GUI application in C++, we would have a method in our GUI-class called WndProc which would receive messages from the operating system, such as WM_KEYDOWN or WM_LBUTTONDOWN (left button down). The WM_KEYDOWN message will only come to us when the user pushes a button and our window is the currently active one, so we can't rely on that one for our global hot-keying. Luckily the people a Microsoft created just what we need; a method in user32.dll called RegisterHotKey( .. ) that allows us to ask the OS:  "Can you please notify me any time the user presses Alt + Z? :)".  If no other application has been granted that combination, the OS will gladly say yes. So from now on when the user presses Alt + Z, our WndProc will receive a message called WM_HOTKEY and parameters explaining which key combination was pressed.


Registering for hot-keys in C#


We need to run the RegisterHotKey method in user32.dll. To get access to this method we import it like this:







// Register a hot key with Windows
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr windowHandle, int id, uint modifiers, uint virtualKey);

// Unregister a certain hot key with Windows
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr windowHandle, int id);




To register a hot-key we must have a handle to our window.

Getting the Handle to our window in a Windows.Form application:

IntPtr handle = this.Handle;





Getting the Handle to our window in a WPF application:

IntPtr handle = new WindowInteropHelper(this).Handle;

Now when we have the handle we can register a hot-key when our window has loaded. The id we use when registering is used later for unregistering. Here is a simple example of registering:

// Register a hot key


if (!RegisterHotKey(handle, 1, (uint) (ModifierKeys.Alt | ModifierKeys.Control), (uint) 'P'))
throw new InvalidOperationException("Could not register the hot key");


Listening to messages in a Windows.Form application


In C# we can create a Windows.Forms application. This is the old school way of creating a GUI application, which was the only way back in the days of .NET 2.x. In a Form class we can override the WndProc and get direct access to the messages that the OS is sending to our window. We can now listen to the WM_HOTKEY message and react accordingly.


Alright, how is this done in WPF?


WPF is very different from Windows.Form and doesn't have a WndProc method. But we will make our own. Let's call it WndProc.



const int WM_HOTKEY = 0x0312;






public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    // check if we got a hot key pressed.
    if (msg == WM_HOTKEY)
    {
        // get the keys.
        uint key = (uint)(((int)lParam >> 16) & 0xFFFF);
        ModifierKeys modifier = (ModifierKeys)((int)lParam & 0xFFFF);

        // invoke the event to notify the parent.
        KeyPressed(modifier, key);
    }

    return IntPtr.Zero;
}



Now we just ask an underlying mechanism of WPF to kindly send us all the messages. We can preferably do this when the window has loaded.

HwndSource src = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); 



src.AddHook(new HwndSourceHook(WndProc));












Summary of global hot-key listening


We have now done the following:
  • Imported the RegisterHotKey( .. ) method from user32.dll
  • Used it to register a hot-key combo i.e Ctrl+Shift+P
  • Getting our code to parse messages in WndProc
    • In Windows.Form: By overriding WndProc( .. )
    • In WPF: By creating WndProc( .. ) and adding a hook
These are the main steps, and our application should now be reacting to the global hot-keys that we want.

Sources and tips

Thanks to Christian Liensberger for his article on hooks in C#.
Thanks to softwerx for his response showing how to use WndProc in WPF.
The Keys enum in Windows.Forms can be used when registering and parsing keys. In a WPF project one can add a reference to System.Windows.Forms and then add:

using FormsNS = System.Windows.Forms;




This will avoid conflicts with MessageBox for example in WPF vs. Forms. We can now easily register and keys like this:

// Register a hot key



if (!RegisterHotKey(handle, 1, (uint)(ModifierKeys.Alt | ModifierKeys.Control), (uint)FormsNS.Keys.Down))
throw new InvalidOperationException("Could not register the hot key");

This way we don't need to define "virtual key-codes", since they correspond to the uint value of keys in Keys.

2 comments:

  1. Great Article...the best explained till now!

    ReplyDelete
  2. hello im abhishek from india i want a project on HOTAL MANAGEMENT in ado.net im confused how to start ..can u advice me some good sites that can help me

    ReplyDelete