Tag Archives: WPF

WPF and Visual Studio Addins

If at all possible nowadays, I write all my Windows UI code in WPF, it’s just quicker and easier than WinForms. Recently however, I came across a situation that you should just avoid.

If you’re developing addins for multiple versions of Visual Studio – don’t use WPF for the Tools > Options windows. It’s just noit going to place nice out of the box. This is because there’s a lot of property page Win32 stuff going on in the host window that makes it hard to route messages properly – keyboard entry won’t work correctly, tab order will be messed up and more, it’s just not worth the pain.

If you’re developing addins for later versions of Visual Studio, you can actually use the VSPackage functionality to build options pages with WPF with ease, just check UIElementDialogPage. In fact, read the article here:

Creating Options Pages by using MPF 

Final thoughts on this – if you want the functionality above in VS2010, you can get it (as long as you use MPF) by checking this page:

Unable to access WPF User Control in Options Dialog

You’ll see that about halfway down, Ryan Moulden has posted some code from Microsoft for the UIElementDialogPage, you can use that you get the functionality in VS2010.

Any other versions, or for a addin installed by an MSI, it’s probably best to stick with WinForms.

 

Introducing FireKeys

I don’t know when I learnt that Windows + E opened up Windows Explorer. It must have been a while ago. But it’s imprinted in my muscle memory, the number of times I hit that combo every day is probably quite high. But how many other hotkeys do I use? Asides from a few other functional ones, like Win + D, I don’t use hotkeys so much. And I got to thinking, I’d love to open Google Chrome with a hotkey just like I do with explorer.

So I wrote FireKeys – a lightweight application that lets you assign hotkeys to actions. These actions could be opening program, a folder or a URL, but the underlying model is designed to be extensible.

FireKeysMain

You can get the tool from the FireKeys page. There’s an article on how it was developed on the CodeProject, FireKeys – Open Programs, Folders and URLs with Hot Keys.

Funky WPF – Enumerations and the Combo Box

Binding a combo box to an enumeration in WPF is more work than it should be, creating an object data provider etc etc:

<Window.Resources>
    <ObjectDataProvider MethodName="GetValues"
        ObjectType="{x:Type sys:Enum}"
        x:Key="CharacterEnumValues">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="Character" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

Followed by

<ComboBox SelectedItem="{Binding Character}"
ItemsSource="{Binding
Source={StaticResource CharacterValues}} "/>

What a pain! I have just added ‘EnumerationComboBox’ to my Apex library – so now you can do this:

<!-- The combo box, bound to an enumeration. -->
<apexControls:EnumerationComboBox 
SelectedEnumeration="{Binding Character}" />

No need for an ObjectDataProvider, an items source or anything – and if you decorate enum’s with the ‘[Description]’ attribute, it’ll use the description in the combo.

There’s an article/download here for anyone who’s interested:

http://www.codeproject.com/KB/WPF/enumcombobox.aspx

MVVM: Asynchronous Commands

The latest cut of the Apex Code (http://apex.codeplex.com/SourceControl/changeset/changes/6701) contains a very cool new feature – Asynchronous Command Objects.

An Asynchronous Command is a ViewModelCommand – the standard object used in Apex for commanding. However, what is different about this function is that it runs Asynchronously.

One of the problems with running a view model command asynchronously is that generally the view model properties cannot be accessed – as they’re created on a different dispatcher. This problem is resolved by using the ‘ReportProgress’ function. Here’s an example:

public class SomeViewModel : ViewModel
{
  public SomeViewModel()
  {
     // Create the command.
     asyncCommand = new AsynchronousCommand(DoAsyncCommand, true);
  }

  private void DoAsyncCommand()
  {
     for(int i = 0; i < 100; i++)
     {
        // Perform some long operation.
        string message = DoSomeLongOperation();

        // Add the message to the View Model - safely!
        asyncCommand.ReportProgress(
          () =>
          {
             messages.Add(message);
          }
        );
     }
  }
  
  private ObservableCollection<string> messages =
    new ObservableCollection<string>();

  public ObservableCollection<string> Messages
  {
     get { return messages; }
  }

  private AsynchronousCommand asyncCommand;

  public AsynchronousCommand AsyncCommand
  {
     get { return asyncCommand; }
  }
}

In this basic mock-up we have a command called ‘AsyncCommand’ (which we could bind a button to for example) which invokes DoAsyncCommand. However, it invokes it Asynchronously. We can also update the ViewModel properties by using ReportProgress – meaning AsyncCommands can seamlessly provide live feedback while they’re working – and we’re keeping well locked in with the MVVM commanding model!

Expect a full article soon on the CodeProject, until then the source is at:

http://apex.codeplex.com/SourceControl/changeset/changes/6701

Drawing a DIB Section in WPF

One of the most exciting new features in the forthcoming SharpGL 2.0 (which was actually planned for 2.1 but has been moved to 2.0) is the facility to do OpenGL drawing in a WPF control. This isn’t done via a WinFormsHost (which has unpleasant side-effects due to Airspace, see http://msdn.microsoft.com/en-us/library/aa970688(v=VS.100).aspx) but actually via an Image in a WPF UserControl.

What does this mean? Well it means that when you use the SharpGL.WPF libraries OpenGLControl you get what is essentially a genuine WPF control – you can overlay other controls on top of it, with transparency and bitmap effects and do everything you’d normally be able to do with a WPF control.

How this works is an interesting bit of code so here are the details.

When using a WPF OpenGL control we render either using a DIBSectionRenderContextProvider, or a FBORenderContextProvider. Here’s the difference:

DIBSectionRenderContextProvider - Renders directly to a DIB Section. Supported with any version of OpenGL but never hardware accelerated.

FBORenderContextProvider - Renders to a Framebuffer object, via the GL_EXT_framebuffer_object extension. This is fully hardware accelerated but only supported in OpenGL 1.3 and upwards. The resultant framebuffer is copied into a DIB section also.

With either render context provider we end up with a DIB section that contains the frame – here’s how we can render it:

/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource HBitmapToBitmapSource(IntPtr hBitmap)
{
    BitmapSource bitSrc = null;
    
    try
    {
        bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
    }
    catch (Win32Exception)
    {
        bitSrc = null;
    }
    finally
    {
        Win32.DeleteObject(hBitmap);
    }

    return bitSrc;
}

This function allows us to turn a handle to a DIB section into a BitmapSource. The OpenGLControl is essentially just an image, and with each frame we simply set the BitmapSource to the newly rendered DIBSection.

The version of the code this post relates to is: http://sharpgl.codeplex.com/SourceControl/changeset/view/4805

The WPF example renders the Utah Teapot (http://en.wikipedia.org/wiki/Utah_teapot) directly in a WPF application. We’re still pre-beta but grab the code if you want to try OpenGL in WPF.