Vista native stuff for WPF

Fri, March 30, 2007, 11:11 AM under Vista | Windows
When I do my talk showing how to call Vista-only native APIs to enhance your Windows Forms applications on Vista, occasionally someone asks about achieving the same in Windows Presentation Foundation (WPF). My answer is always the same of course: "WPF does not include any Vista-only APIs so you still have to pinvoke for the features that I demonstrate."

For example, many features rely on overriding the WndProc method to hook into the main message loop and deal with some windows message (WM_):
  protected override void WndProc(ref Message m)
{
// e.g. deal with message for
// composition changed, power state notification, restart manager aware etc
}
In WPF you can achieve that with code like this:
       void Window1_Loaded(object sender, RoutedEventArgs e)
{
source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
}

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// TODO handle WM_
}
While the previous statement/reply/example is true, some of the things I show in my talk rely on using a control's handle. For example, adding a shield to a button (for UAC), the new button style known as CommandLink, TextBox cue banner, Vista TreeView etc. In those cases, for WPF you can't use pinvoke to SendMessage or subclass the control (Get/SetWindowLong etc) since the WPF controls are drawn from scratch. Instead, you have to manually draw the effect you are after. The Windows SDK has an example of a CommandLink fully drawn for WPF but I couldn't see any of the others (e.g. a button with a shield) so this is a great opportunity for a WPF developer to flex their creativity muscles and create the Vista control behaviours/appearances for WPF (since pinvoking doesn't help there). Be sure to let me know if you get round to implementing anything like that in the public domain...