Pixel-perfect Multi-DPI Images in WPF (Part 1)

View source on GitHub.

See also: Part 2 and Part 3.

I’ve written previously about DPI-awareness in the Windows Presentation Foundation and how to specify measurements in pixels rather than Device Independent Units (DIUs). Something else to consider is image scaling – unlike the Windows Ribbon control or WinRT, WPF has no in-built mechanism for displaying different images according to the system’s DPI setting. This is a nuisance.

To illustrate the problem, I created 5 images. Left-to-right, the image DPIs (vertical and horizontal) are: 72, 96, 120, 144 and 192. The image dimensions are: 32x32px, 32x32px, 40x40px, 48x48px and 64x64px. I purposely used single-pixel-wide lines to make any stretching obvious.

Original Images

Read on to see what WPF does with these images.

Continue reading “Pixel-perfect Multi-DPI Images in WPF (Part 1)”

P/Invoke and ChooseFont (Comdlg32.dll)

Mister Goodcat wrote a good article a little while ago about using P/Invoke in Silverlight 5 to display the native font chooser dialog with the ChooseFont function. I couldn’t get the code working for a 64-bit executable, however, as the definition of the CHOOSEFONT structure on MSDN he used as a basis for the managed implementation doesn’t match with what’s in the Windows SDK. I’ve created a page on PInvoke.net for the function that includes a definition of CHOOSEFONT that works in both 32-bit and 64-bit versions of Windows.

Screenshot of Font Chooser Dialog

Retrieving Windows 8 Theme Colours

See also: Windows 8 Theme Colours Reference.

Windows 8 doesn’t offer developers access to system theme colours, unlike its cousin, Windows Phone. Even for a version 1 product, this seems like a strange omission. Then again, we still don’t have a working public API for retrieving the Aero glass colour (or whatever we call it now that Aero’s gone) 6 years after the release of Windows Vista.

The functions that the system uses to retrieve colours are defined in UxTheme.dll. In particular, we’re interested in GetImmersiveColorSetCount (export #94), GetImmersiveColorFromColorSetEx (export #95), GetImmersiveColorTypeFromName (export #96), GetImmersiveUserColorSetPreference (export #98) and GetImmersiveColorNamedTypeByIndex (export #100). Relying on undocumented functions is a bad idea, and will cause your program to fail certification, so you won’t be able to use them in apps distributed through the Windows Store anyway.

For desktop developers who still want to use these functions, read on. Just assume that they’ll break in future versions of Windows (or even with patches to Windows 8).

Screenshot of Windows 8 Colours

Continue reading “Retrieving Windows 8 Theme Colours”

Keiki Usage Meter 3.1.0 Released

I’ve released an update for Keiki Usage Meter. There has been a lot of behind-the-scenes work, but the user experience hasn’t changed drastically. Visit the website to find out what’s new.

I’m using this program as something of a testbed for some engineering work that I’ll talk about in future posts, including supporting pixel-perfect bitmap images at multiple DPI settings in WPF and using the Visual Styles APIs to draw native-looking controls (with animation). I’ve also taken the opportunity to learn a bit about localising programs, and v3.1.0 contains three user interface languages: English (Australia), English (United States) and Japanese (Japan) – thanks to Miho Inaba (稲葉美穂) for help with the latter.

WPF: Using System Colours in Animations

WPF provides access to the Windows system colours through the System.Windows.SystemColors class. As the MSDN documentation indicates, it’s possible to bind to these colours dynamically using the *Key resources, so when the system colours change, so will the appearance of your application.

This code will set the colour of a TextBlock to the ‘GrayText’ system colour, and will change automatically if the user switches themes:

In many cases, there’s no reason not to bind dynamically. Problems arise with animations, however. From MSDN:

You can’t use dynamic resource references or data binding expressions to set Storyboard or animation property values. That’s because everything inside a ControlTemplate must be thread-safe, and the timing system must Freeze Storyboard objects to make them thread-safe. A Storyboard cannot be frozen if it or its child timelines contain dynamic resource references or data binding expressions.

This means that you’re stuck using static references to system colours in your animation storyboards – if the user changes the system colours while your application is running, your storyboards won’t update automatically. Worst-case scenario, you might end up with unreadable text.

I don’t think there are any workarounds that don’t involve reloading windows and/or resource dictionaries (depending on where the style code is located). Reloading a window is easy enough – just be careful if you’re closing your application’s last window: the program will shut down if there are no remaining references to any windows.

The method for reloading a resource dictionary is a bit less obvious. It seems that XAML files accessed by their pack URIs are already compiled, so the system colours will be fixed in place once the program starts up. To get around this, change the build action for the XAML file containing the resource dictionary to ‘Embedded Resource’. You can then (re)build the resource dictionary as you please using XamlReader:

Remove the old resource dictionary from your application’s merged resource dictionaries, then add the new one.

Creating a new resource dictionary like this seems to be fairly slow, so try to avoid doing it on a regular basis. To tell when the Windows theme or system colours have changed, you’ll need to listen for the window messages WM_THEMECHANGED and WM_SYSCOLORCHANGE. See this post for information about listening for window messages in WPF.

Drawing non-themed push buttons in Windows

When visual styles are enabled in Windows, one may use the DrawThemeBackground function to draw themed push buttons. However, users of Windows XP, Windows Vista and Windows 7 can disable visual styles by selecting the Windows Classic theme or one of the High Contrast themes (and in Windows 2000 and earlier, visual styles weren’t available at all). The classic theming mode has been removed in Windows 8 (I have written about this previously), so in that OS the visual styles APIs should always be available. I suspect it will be a long time before NT6.1 and earlier versions of Windows constitute an insignificant share of the market, though, so this post should be useful until then.Screenshot of Non-Themed Buttons

There are four states that a non-themed button can be in: normal, pressed, defaulted or inactive. How can we draw these states?

The rough non-themed equivalent of the DrawThemeBackground function is the DrawFrameControl function. It has a parameter uType that specifies the type of the frame control to draw – in our case, this should be DFC_BUTTON (= 4). The next parameter is uState. We should set this to DFCS_BUTTONPUSH (=0x0010). For the normal state, this is all that needs to be done. For the inactive state, we should set uType to DFCS_INACTIVE (=0x0100) | DFCS_BUTTONPUSH (in fact, this doesn’t seem to change the appearance of the button frame; the button content/text should be rendered as gray, but that’s out of the scope of this article).

When a non-themed button is pressed or defaulted, it has a single pixel border drawn around it, and the frame control’s bounding rectangle is contracted by 1 pixel on each side. The border’s colour is that of the window frame (COLOR_WINDOWFRAME = 6) – you can use the GetSysColorBrush function to get the appropriate brush. For the defaulted state, just call DrawFrameControl with uType set to DFCS_BUTTONPUSH (with the deflated rectangle). For the pressed state, it might seem like DFCS_PUSHED should be used for uType, but this creates an appearance different to that of standard push buttons. This style is used elsewhere, like on the Windows taskbar, for scrollbar buttons and window caption buttons, etc. Internet Explorer’s owner/custom-drawn buttons also use this style, and I’m sure many other programs do, too. It should be avoided, however, if you’re seeking the native appearance. To properly imitate a pressed push button, avoid using the DrawFrameControl function and use the FrameRect function to draw an inner border with the button shadow colour (COLOR_BTNSHADOW = 16). It’s important to then use the FillRect function to draw the background with the button face colour (COLOR_BTNFACE = 15).

Here’s some pseudocode to illustrate the whole process:

In addition to drawing the background, note that for all states but pressed, the content (text) should be shifted one pixel left and one pixel up. When the button is pressed, it should move one pixel right and one pixel down, so it is centred in the button. Some owner/custom-draw implementations neglect this detail.

Facebook Messenger for Windows is not just for Windows 7

Facebook recently launched ‘Messenger for Windows’, a desktop client for Facebook chat.

The Messenger for Windows help page suggests that the program requires Windows 7:

What kind of computer operating system do I need in order to use Messenger for Windows?
You can set up the app if you use Windows 7 on your computer.

In fact, it runs perfectly well under Windows Vista with the .NET Framework installed. In Windows XP, it crashes on load (though the notification area icon appears first):

Screenshot of Facebook Messenger for Windows (XP)

Looking at the executable in .NET Reflector, the program uses the functions DwmSetWindowAttribute and DwmExtendFrameIntoClientArea, which are not available in Windows XP. I suspect that adding support for that operating system wouldn’t be very difficult, however, as the program is little more than a couple of WebBrowser controls (the heavy lifting is not done on the client side).

Given that Facebook decided not to support Windows XP, the least they could do is use a task dialog instead of this:

Screenshot of Facebook Messenger for Windows dialog

If you look closely, you’ll notice that the font is Microsoft Sans Serif, not Segoe UI (the latter is the user interface font in Windows Vista and newer – MS Sans Serif hasn’t been the default since Windows ME!). This is largely Microsoft’s fault – MS Sans Serif is the default font in the Windows Forms designer even in Visual Studio 2010 (and the issue has been around for a long time) – but it’s something that the Facebook developers should have picked up on.

I was disappointed to see that the application is installed to the ‘local application data’ folder (C:Users<User>AppDataLocal in Vista and newer) instead of Program Files. I guess when Google decides it’s acceptable to install Google Chrome in %appdata%, everything is permitted. (Microsoft itself is hardly blameless – ClickOnce applications are installed to somewhere non-standard.)

Interestingly, the developers chose to use the CS_DROPSHADOW window class style to draw a shadow around the window even when the DWM is disabled. Given that Google returns fewer than 10,000 results for CS_DROPSHADOW, this must be one of very few applications to use that feature.

(As the screenshot below demonstrates, running the program with IE7 installed produces hilarious results.)

Screenshot of Facebook Messenger for Windows (Vista)

The program doesn’t respect the operating system’s language settings – the notification area icon’s menu is displayed in the language that the user selects on Facebook.

Finally, the docking functionality is implemented by using an application desktop toolkbar (appbar). I haven’t seen many programs use appbars, so it’s neat to see one in action.