Sunday, July 27, 2008 - 19:36:47 GMT
Random Quirks

Having recently converted my last machine to Vista, I bid farewell to some interesting quirks that were visible in XP (the last of which still works on Vista sometimes). Find yourself an XP machine and give them a try if you're bored sometime.


Sticky Buttons

This one is first because it has been around for ages.

1. Find a regular toolbar (WordPad, Address Book, HyperTerminal, etc.)
2. Move your mouse over a button
3. Press down the right mouse button
4. Press down the left mouse button
5. Release both buttons (in any order)

The toolbar button will now stick down, and any other buttons you click (using just the left mouse button will do) will also stick down. If the toolbar can be reordered (e.g. in WordPad), clicking the menu while buttons are stuck down usually does bad things as well.


Speed Up Your Computer

With this handy tip, you can make your computer complete some tasks at high-speed! (or at least make it look that way).

1. Find a "marquee" progress bar (e.g. the one shown while clearing the cache in IE 7).
2. While it's moving, drag another window overtop of part of it.

As long as a window is moving overtop of it, the bar will run at high-speed. Dragging overlapped windows doesn't trigger redraws in Vista, so this behavior can't be seen anymore. If you are curious whether it has actually been fixed or not, feel free to write some code to trigger repaints.

If you don't have IE 7 (or don't have enough cache built up to make clearing take a while), you can grab a little application to make a progress bar here. If you don't trust random applications from some guy's blog, you can use the following code (be sure you update the manifest to use common controls version 6, as the marquee style isn't available in previous versions):


#include <windows.h>
#include <commctrl.h>

LRESULT __stdcall MessageHandler(HWND window, unsigned int message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_CLOSE:
            DestroyWindow(window);
            break;
        case WM_DESTROY:
            PostQuitMessage(69);
            break;
    }

    return DefWindowProc(window, message, wParam, lParam);
}

int main()
{
    HINSTANCE instance = GetModuleHandle(NULL);

    INITCOMMONCONTROLSEX commonControls;
    commonControls.dwSize = sizeof(INITCOMMONCONTROLSEX);
    commonControls.dwICC = ICC_PROGRESS_CLASS;
    InitCommonControlsEx(&commonControls);

    WNDCLASSEX windowClass;
    windowClass.cbSize = sizeof(WNDCLASSEX);
    windowClass.cbClsExtra = 0;
    windowClass.cbWndExtra = 0;
    windowClass.lpszMenuName = NULL;
    windowClass.style = NULL;
    windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW
+ 1);
    windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
    windowClass.hInstance = instance;
    windowClass.lpfnWndProc = MessageHandler;
    windowClass.lpszClassName = L"MainWindow";
    RegisterClassEx(&windowClass);

    HWND window = CreateWindowEx(NULL, L"MainWindow", L"violus.com",
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 10, 10, 300, 100, NULL, NULL, instance, NULL);
    HWND progressBar = CreateWindowEx(NULL, L"msctls_progress32",
L"ProgressBar", WS_CHILD | WS_VISIBLE | PBS_MARQUEE, 5, 5, 250, 25, window, NULL, instance, NULL);

    SendMessage(progressBar, PBM_SETMARQUEE, 1, 100);

    MSG message = { 0 };
    while (GetMessage(&message, NULL, 0, 0) != 0)
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    return 0;
}



JMP In Your IDE

This last one is only available to people with the Visual Studio IDE (be it Visual Studio, Visual C# Express, whatever).

1. In Visual Studio 2005 or 2008, open a text file long enough to be able to scroll vertically
2. Using the mousewheel, scroll down as far as you can
3. Open Internet Explorer 7 (maybe others work?) infront of Visual Studio so you can still see your text file
4. Select Tools -> Delete Browsing History -> Delete All

And there you have it (if it worked). The first two behaviors have fairly obvious explanations (not handling interleaved button presses, and changing progress state in the redraw code), but this one is a bit stranger. Evidently, clearing the cache in IE gets a message to Visual Studio (possibly because newer versions of Visual Studio host the webbrowser control), and that message triggers the text editor to scroll. Some debugging (or maybe even just Spy++'ing) would likely reveal the source of this behaviour, so go ahead and try it if you care enough. I don't.

desktop misc
Friday, July 25, 2008 - 1:47:45 GMT
Bindings Need a Home Too

When you imagine a high level view of a two-way binding, you might think of something like this:



Although this is true in function, it doesn't quite match the WPF implementation. WPF's dependency properties can hold a couple different things. That "thing" can be a specific value, or a binding that receives change notifications and updates the value as necessary (as well as pushing out local changes, in the case of a two-way binding). This is a simple enough concept to grasp, and its implications are pretty clear: bind a property to something and its value will be overwritten, assign a value to a property and its binding will be overwritten.

Where this whole setup can catch you off guard is with chains of bindings. For demonstration purposes, imagine you want to create a number editing control that allows a user to manipulate a number in a variety of ways:



The conceptual binding map would probably look like this:



But remember, bindings need to be set on a property; bindings need a home! Where you choose to place the bindings can cause some trouble. For example:



The layout above clearly won't work. A single property can't be bound multiple times. Whichever binding was set last on each property will remain, all others will be overwritten, and the chain will be broken.

Although it's easy to spot the error in a high-level view, it's fairly easy to make a mistake like this. A common example is setting a single binding within a chain of classes, without checking the code of all the other classes in the chain. To solve this problem in a clean manner, you must choose to always set bindings on items higher up the chain, or always set bindings on items lower down the chain.

If you are the only one that will ever see your code, and you're sure you will remember your pattern absolutely everywhere, you could always set the binding on the items higher in the chain. If you ever plan to reuse the code elsewhere, or just want to allow a little room for error, you should probably set bindings on items lower in the chain.



As you can see above, setting the binding higher in the chain results in the component's public interface having a binding already set on it. The user of the component may not know your little pattern and try to use that property. If the user simply assigns a value to the property (or sets a binding on the property) your binding will be overwritten, magically breaking the chain and rendering the control useless. Always binding to items lower in the chain isolates your pattern to your control and lets users do whatever they please. Setting bindings higher in the chain spreads the requirement outsite of your control to everyone who uses it.

code
Sunday, July 13, 2008 - 3:41:45 GMT
The WPF Forest, Part 2

The logical tree takes care of delegating control content rendering, so what about rendering the control itself? This is where the visual tree comes into play. To make control customization and themes both flexible and easy, most objects are actually an aggregation of other objects. A listbox might be a Border, containing a Grid, containing a StackPanel and ScrollBar. This allows individual parts of the control to be changed independently. In addition, if the scrollbar is customized for an appliction, that customization can propagate into the scrollbar inside the listbox, giving the application a consistent look and feel. This set of objects used to render the control itself are in the visual tree, and not in the logical tree.

In short, because WPF uses a hierarchy of objects to draw a single control, navigating the actual object hierarchy is fairly problematic. When you get the children of a listbox, you probably want the items it contains, not the border, grid and scroll bar it uses to render itself. The visual tree is the tree of objects that will actually be drawn, while the logical tree "skips" the objects used solely for drawing, giving you a control-level view of the hierarchy. The logical tree allows you to navigate the hierarchy of controls that you put together (e.g. a picture inside a button inside your window), without worrying about what objects make up the internals of each control. The visual tree contains the "actual" hierarchy, so that every item can be found and rendered.

It's worth noting that different parts of WPF use different trees. The most common ones you'll encounter are routed events and resources. When an event bubbles up the hierarchy, or tunnels down the hierarchy, it navigates the visual tree. This ensures any visual elements can update appropriately as states change. Resource location, on the other hand, navigates the logical tree, searching logical parents for the requested resource.

code desktop
Saturday, July 12, 2008 - 3:16:22 GMT
The WPF Forest, Part 1

Ordering components in a hierarchy has been a pretty standard procedure in user interfaces for quite some time. When programming regular Win32 applications there is a single tree of objects. Each object (be it a button, textbox, or top-level dialog) is a rectangular region called a window, and can be manipulated via a handle (HWND). Windows handle both logic and appearance via input messages and paint messages.

Windows Forms follows the same hierarchy, as it is a wrapper for the Win32 system. Ideally, this provides you with the same familiar control model, in an easy-to-use wrapper.

WPF is based on a completely different model. Components are no longer separate windows; your application is contained in a single top-level window. Once inside the top-level window, it's all WPF land: the controls have been re-written in the WPF framework rather than simply wrapping the old controls, and there's not a HWND in sight.

With this new framework came a new way of organizing controls. There is no longer just a single tree of elements, but several trees. Alright, there's really just two. Not quite a forest, but still more than one.

The first tree is very similar to the single Win32 window tree, as well as the logical way people think about a hierarchy of controls. It is called the Logical Tree, and can be manipulated via a LogicalTreeHelper (although that shouldn't be necessary). Like the Win32 window tree, you can nest children within children arbitrarily deep. Although similar in nesting controls within parents, WPF does require a bit of a mindset shift.

Win32 windows can be nested, but most controls don't actually expect it. Instead, Win32 controls are designed to handle a specific kind of data, which is typically populated through messages. For example, a listbox is populated by sending it a message with a string to add. The control stores the list of strings in a private location, drawing it as necessary. This means control content does not show up in the tree of windows, and if you want something other than just text, you have to extend the listbox to draw what you want.

In WPF, controls are designed to host children instead of data (e.g. put a picture in a button, and that button in a listbox). The parent is responsible for drawing only its own visuals; the content is a separate object that is capable of rendering itself. Although this hierarchy can be manipulated with the VisualTreeHelper, this is typically unnecessary as controls should expose their (logical) children to be easily changed at runtime. A window has a "Child" property. A grid has a "Children" property. A ListBox has an "Items" property, and a button has a "Content" property. It's all fairly logical.

code desktop
Monday, June 30, 2008 - 2:53:56 GMT
References Behind the Scenes

Moving to a garbage-collected framework like .NET lets you forget about some simple memory-management cases, but also makes you consider some hidden cases that would have been explicit in a framework without garbage collection. As motivation, here is a simple example: You create a timer to wait some interval, then call a method on a target object. What happens if you have no references to the timer? Does it never fire? What happens if you have no references to the target object? Does the method call never happen? Does the method get called on a deleted object? A simple example can illustrate the behavior.


public class Program
{
    class SelfDestructor
    {
        private byte[] spaceWaster = new byte[1048576];

        public SelfDestructor()
        {
            Timer timer = new Timer(10000);
            timer.Elapsed += new ElapsedEventHandler(OnTimer);
            timer.Start();
        }

        void OnTimer(object sender, ElapsedEventArgs eventArguments)
        {
            (sender as Timer).Stop();
        }
    }

    static void Main(string[] arguments)
    {
        for (int index = 0; index < 100; index++)
        {
            new SelfDestructor();
        }

        while (true)
        {
            GC.Collect();
            Console.WriteLine("Using: " + (GC.GetTotalMemory(false) / 1048576) + "MB.");
            System.Threading.Thread.Sleep(1000);
        }
    }
}


As C# doesn't provide destructors (I don't feel like using disposable objects), we may as well go straight to the source: the memory. The code shown above creates a pile of large objects with timers waiting to call one of their methods. The code above maintains no references to the timers or the target objects. The output you'll observe is:


Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 100MB.
Using 0MB.


This output answers all of the questions. If you think about them, all of the results are fairly logical. It's just good to know for sure.

The most obvious observation is that at the 10 second mark the timer did fire, showing that queuing the timer to fire maintained a reference behind the scenes, keeping the timer alive. As the timer event actually fired properly (as opposed to exploding), it's safe to conclude that the waiting timer also maintained a reference to the object it would call into, keeping the target object alive. The final observation is that all of the objects were freed from memory when the timer was stopped. With the timer stopped, it need not remain in the queue, dropping the reference to the timer. When the reference to the timer is dropped, there are also no more references to the target objects.

The take home lesson? You won't miss timer events, even if you don't hold your own references to the timer or target object, only so long as the timer is running.

On to the main point of this entry: data binding references. If you've used WPF much at all, you've almost certainly made use of some data bindings. You can create some objects and set a binding to automatically keep various properties synchronized. The question is: if you forget to clear a binding, or simply overwrite a binding, will the bound objects persist? Will values continue to get propagated? A bit more code will take care of these questions.


public partial class MainWindow : Window
{
    class BindingObject : DependencyObject
    {
        public static DependencyProperty NumberProperty = DependencyProperty.Register("Number", typeof(int), typeof(BindingObject));
        public static DependencyProperty StringProperty = DependencyProperty.Register("String", typeof(string), typeof(BindingObject));

        private byte[] spaceWaster;

        public BindingObject(int size)
        {
            spaceWaster = new byte[size];
        }

        public int Number
        {
            get { return (int)GetValue(NumberProperty); }
            set { SetValue(NumberProperty, value); }
        }

        public string String
        {
            get { return (string)GetValue(StringProperty); }
            set { SetValue(StringProperty, value); }
        }
    }

    private int secondsElapsed = 0;
    BindingObject parent = new BindingObject(0);
    BindingObject targetChild = new BindingObject(1024 * 1024 * 10);
    BindingObject sourceChild = new BindingObject(1024 * 1024 * 10);
    Timer timer = new Timer(1000);

    public MainWindow()
    {
        InitializeComponent();

        Binding binding = new Binding();
        binding.Source = parent;
        binding.Mode = BindingMode.TwoWay;
        binding.Path = new PropertyPath(BindingObject.NumberProperty);
        BindingOperations.SetBinding(targetChild, BindingObject.NumberProperty, binding);

        binding = new Binding();
        binding.Source = sourceChild;
        binding.Mode = BindingMode.TwoWay;
        binding.Path = new PropertyPath(BindingObject.NumberProperty);
        BindingOperations.SetBinding(parent, BindingObject.NumberProperty, binding);

        binding = new Binding();
        binding.Source = sourceChild;
        binding.Mode = BindingMode.TwoWay;
        binding.Path = new PropertyPath(BindingObject.StringProperty);
        BindingOperations.SetBinding(targetChild, BindingObject.StringProperty, binding);

        timer.Elapsed += new ElapsedEventHandler(OnTimer);
        timer.Start();
    }

    void OnTimer(object sender, ElapsedEventArgs eventArguments)
    {
        secondsElapsed++;
        if (secondsElapsed == 10)
        {
            sourceChild = null;
            targetChild = null;
        }

        GC.Collect();
        Console.WriteLine("Using " + (GC.GetTotalMemory(false) / 1048576) + "MB");
    }
}


This code creates more large objects, but instead of connecting a timer to them, it connects a few properties. To cover just about every way values could be propagated, the "child" objects have two-way bindngs, are both binding sources and binding targets, and are bound to eachother:



A reference to each child is held until 10 seconds have passed, then the references are dropped. The output this time?


Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 20MB.
Using 0MB.


As you can see, the large child objects were removed when their explicit references were dropped. This reveals a convenient aspect of WPF's data bindings: they hold no references. You can set as many bindings as you like, interconnect properties in a convoluted mess, then simply forget about the objects when you are done with them. The objects will still disappear, even if their bindings haven't been explicitly cleared, and they will stop updating other objects.

It appears that both timers and data bindings perform in the way that is most convenient for common situations. For uncommon situations, it is worth knowing their behavior:

* When neither your code nor the visual tree of objects has a reference to a control, it will be disconnected and deleted automatically.

* When you no longer reference a timer or the object receiving timer events, both will be persisted automatically. If you are in this situation, you can obtain a reference to the timer from the event's "source" argument to stop the timer and release the objects.

code
Monday, June 9, 2008 - 23:10:41 GMT
I'll Take Care of the XAML, Thanks.

I like to write the HTML for my sites in a simple text editor. I developed this preference because it provides me with more control (the ability to write anything, not just what an editor can generate), as well as fewer frustrations (when an editor encounters a manually-added section that it doesn't understand, it can either ignore it and render incorrectly, or overwrite it). This is, of course, just my preference. You may prefer a visual text editor.

In any case, given my HTML-writing habits, combined with some really good Intellisense, it's fairly obvious that I'd prefer to write XAML myself as well. Unfortunately for me , the default action when opening a XAML file in Visual Studio is to parse the document, then populate a visual editor with controls representing each part of the document (quite slowly sometimes, I might add). Thankfully all of this can be fixed.

If you use Visual C# Express (and probably other versions as well), can find a useful setting by doing the following:

- Go to Tools -> Options in the IDE
- Check the "Show All Settings" box
- Navigate to Text Editor -> XAML -> Miscellaneous
- Check the "Always open documents in full XAML view"

This setting does exactly what I'd like to see. By default, documents are opened in a full-window XAML editor (not a split-pane view), and the parsing/population for the visual editor is not done at all, keeping things nice and quick. Should you want to use the visual editor on occasion, the Designer tab is still present. Inside the designer pane is a link to populate the designer, without the need to change any settings back.

As a side note: If you've used Visual Studio before, you'll notice that the express edition no longer shows Debug and Release build configurations. If you plan on releasing your application, or just want multiple configurations, you'll probably want these back. With "Show All Settings" checked, in the "Projects and Solutions" entry you can find a checkbox labeled "Show advanced build configurations".

code
Tuesday, May 20, 2008 - 23:28:15 GMT
Where Did The Mouse Go?

So you're all settled into the WPF world. After making some nice templates for controls, you may decide to make a few changes to your main window as well. Maybe you add in a few transparent regions, maybe remove the whole background.. then BAM! no more mouse events for you!

The world of WPF rendering is a pretty convenient place, letting you layer and shape objects however you want, without being restricted to rectangular bounding boxes, or managing intricate (and sometimes moving) window regions. Unfortunately, there's a big world around it, and you can't always ignore it.

The problem arises from the difference between a null brush and a transparent brush. More specifically, the lack of a difference in this case. In WPF "null" means "nothing's here, don't do anything with this area", and transparent means "something's here, you just can't see it because it's filled with the solid color #00xxxxxx". When all of the WPF rendering is done, the result appears inside a regular win32 layered window. Layered windows can provide all of the irregular regions and alpha blending that WPF needs, but it does not provide a transparent-but-solid state.

When you populate a layered window (with UpdateLayeredWindow, for example) you simply give it bitmap data without any extra data to imply whether a region is solid or not. Instead, layered windows infer whether a pixel is "solid" or not based on its opacity: #0100FF00 is a very translucent green, while #0000FF00 is not a solid color at all, but an "empty" pixel that should not generate input. Whether you make your WPF color null or transparent, the end result is a pixel with an alpha value of zero, hence, no input is generated from it at the window level. If the event is never generated at the window level, it will never be passed down to the WPF level where the decision can be made whether the pixel is actually null or merely "transparent".

The solution to this problem should be fairly obvious by now. Using transparent (but solid) colors in WPF is fine, so long as something solid is behind it. If the end result of rendering your entire window has any transparent pixels left, they will generate no mouse input, regardless of whether WPF thinks they are transparent or null. If you need mouse input for these areas, you will have to pick a color with a non-zero alpha value (e.g. #01808080). Blending with an alpha value of 1 (an opcaity of approximately one-third of one percent) produces an acceptably negligible difference in color, while restoring mouse input to your application.

If you're worried about having some ugly box around your application, take a quick look at the math:



The maxiumum difference from the original value will occur when the background color has a value of 0, yelding a difference of 0.5 out of 255. In all other cases the difference is less than 0.5. As color values are rounded or truncated to integral values, this means the that not only should the difference be imperceptible, the vast majority of the time there should be no numerical difference at all.

code desktop
Monday, May 19, 2008 - 1:48:46 GMT
Starting Fresh

It's back!

Violus.com is (somewhat) new and (mildly) improved! Most importantly, all of the old stuff has been cleared out. Although the few articles that received a larger number of hits will return, almost everything will be new.

As far as I can tell from how blogs seem to be run, this one should be a huge success: I've got some category tags that I'll probably forget to use, a boring little blurb about me in the corner, and an excessively long list of links that nobody cares about down the side of the page. Everything seems to be in order here.

misc