If you target your application to run on the Windows 7 which will be broadly available on October 22nd, you definitely need to read this article as it will show you how to build applications using the .Net Framework that can access some new features of Windows 7. If you are not planning to run your apps on Windows 7 any time soon but they are currently running on Vista and/or Windows Server 2008, many features explained here are also valid (in this article, I have tested the feature on Windows 7 and Vista and tell you on which OSes they are working). The features of this API Code Pack are not available in the .Net Framework 3.5 today (and I have not seen any clear commitment that they will be available directly in the upcoming .Net Framework 4.0).
In December 2008, I wrote an article on the Vista Bridge, the Windows API Code Pack is an evolution of it. This new package goes beyond what was offered into the Vista Bridge with features that are unique to Windows 7.
This is the first part of a 2-parts article. This month I will explore a set of features and next month (November 2009), I will explore more features like the Jump List and Thumb nails. So stay tuned!
What do you need?
You first need to have Visual Studio 2008 SP1 and the application you are building must target the .Net Framework 3.5.
To be able to test all the features of this code pack, you will also need Windows 7 RTM version (as some features have changed since the beta or the RC version). Some of the features might also work on older version of Windows.
Lastly, you will need the Windows API Code Pack itself. You can download it from the MSDN Code Gallery web site.
The files to download
The first file to download is WindowsAPICodePack.zip and is about 7 MB to download. It contains the source code of the library. Once downloaded, extract the files from it and you will discover 2 main folders. The first one is WindowsAPICodePack and it contains a .Net solution. The first thing you need to do is to open this solution in Visual Studio 2008 SP1 and build that solution to ensure you have everything in place to go further. This zip file also contains a samples folder that we will explore a bit later.
The other file you really should download is the WindowsAPICodePackHelp.exe which is over 4 MB to download. This file is a self-extracting zip file containing a single file: WindowsAPICodePack.chm containing all the help you can get for this code library. Don’t expect too much of the help file. In my case, I wanted to know what properties and methods were really doing and when to use them. I have a lot of topics in it and never found something helpful! I really hope the team will spend more time completing it.
The 2 other files you can download are about DirectX and I won’t explore those features here.
The official web site
The Windows API Code Pack for Microsoft .Net Framework official URL is http://code.msdn.microsoft.com/WindowsAPICodePack. The current version is 1.0 and was released on August 6, 2009.
This web site offers the latest version to download the source code of the component, samples and help files. It also offers sections for discussions and to track issues.
What are the features?
The official list of the 14 features supported in version 1.0 of the package is:
Exploring the samples
After you downloaded and unzipped the WindowsAPICodePack.zip from the MSDN Code Gallery, you should be able to find a sub-folder named Samples which contains many samples in both VB and C#. Some of the samples are also available in both Windows Forms and WPF forms. Each subfolder contains its own solution so you need to navigate a bit to open each solution one after another.
My own sample
Instead of guiding you through the samples provided by downloadable package, I have decided to create my own set of samples with some of the features (I really don’t want to cover them all).
I have been very lazy this month for my downloadable demo code. I have only provided VB code. I am sure C# developers will be able to understand the very little code found here and also the samples provided by Microsoft are offering both VB and C# versions of their own demos.
File and Folder Dialog Box
The first feature I want to explore is an easy one to kind of start slowly. The features I want to explore here are related to the file dialog boxes (open/save), folder dialog box (this is new) and the new Explorer browser control. All those features are related to let users of your applications selecting a file or a folder or a resource.
I already hear you say that the .Net Framework already provides a File Dialog box (you can find an introduction article here). So if you need to let the user select a file, you surely have some code that looks like this:
Dim d As New OpenFileDialog
If d.ShowDialog = Windows.Forms.DialogResult.OK Then
MessageBox.Show("You have selected : " + d.FileName)
But if you replace the declaration with this new one, you will get exactly the same dialog:
Dim d As New Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog
This new class works on Windows 7 as well as Vista. Up to this point, there is no advantage in using the newer class but there are a couple of interesting features that the new API gives us.
The first benefit from this newer class comes from its IsFolderPicker property (which is false by default) which will transform the file picker to a folder picker (works on Win7 and Vista). The dialog won’t show any files, only folders. Using exactly the same as previously shown, you just have to add this simple line before calling the ShowDialog method to enforce the new behaviour (you even use the FileName property to return the name of the selected folder):
d.IsFolderPicker = True
Another interesting feature of this class comes from the known folders. This feature lets you open the dialog to a folder by default without having to know the name of that folder. Windows has a complete list of folders that you can set using the KnownFolders enumeration. You will find many folders in this enumeration (about 50 values) like MusicLibrary, Documents, ControlPanel, Contacts, Printers, Pictures, and much more. To initialize the initial directory, you just need to set a property before you call the ShowDialog method:
d.InitialDirectoryShellContainer = CType(KnownFolders.MusicLibrary, ShellContainer)
But be warned that this feature is only available on Windows 7. To protect yourself against an exception, you should check to see if the OS supports the feature by using this code:
If ShellLibrary.IsPlatformSupported Then
This property will return True if your OS supports features offered by the Shell Library like this one.
Explorer browser control
Sometimes, the standard dialog is not really what you want. In the past, you had to build your own control to enable the user to browse and select files and/or folders. Now, the Windows API code pack provides a control that you can embed into your own forms that offers the same behaviour as Windows Explorer. One good news is that this control works on Vista as well.
Figure 1: The New Explorer control in action
In the previous figure, you may note that at the top of my form, I have 3 buttons. The control itself does not provide easy validation in some case. For example, if you navigate to the control panel, you will lose the treeview control on the left and there is no easy way to go back from there. That’s why I have created my own navigation buttons and a button to display the currently selected file. In my demo, I also enable/disable the navigation buttons when it makes sense.
The complete code to initialize the control, navigate and display the selected file is the following:
Private Sub fExplorerControl_Load() Handles MyBase.Load
'disables the naviagation buttons
btnNext.Enabled = False
btnPrevious.Enabled = False
explorerBrowser.ContentOptions.SingleClickActivate = True
'when the form is loaded, navigate to the desktop by default
Private Sub btnPrevious_Click() Handles btnPrevious.Click
'when the Previous button is hit, we can navigate using the history
Private Sub btnNext_Click() Handles btnNext.Click
'when the Next button is hit, we can navigate using the history
Private Sub explorerBrowser_NavigationComplete() Handles explorerBrowser.NavigationComplete
'each time the control navigates, we check if we can enabled the previous and/or the next buttons
btnPrevious.Enabled = explorerBrowser.NavigationLog.CanNavigateBackward
btnNext.Enabled = explorerBrowser.NavigationLog.CanNavigateForward
Private Sub btnSelect_Click() Handles btnSelect.Click
'Displays the first selected item
MessageBox.Show("you selected: " + explorerBrowser.SelectedItems(0).ParsingName)
It is not that bad considering that most of the code here is to enable/disable the navigation buttons!
Another area where the Windows API Code pack offers great improvements over the regular .Net Framework is that it is a lot easier to create rich message box. This feature works on Vista and Windows 7 correctly.
For those of you who could have tried the Vista Bridge in the past, it is almost the same thing. They changed the namespace and a couple of property names but almost everything else remains exactly as it was before, bugs included! In my Vista Bridge article of last year, I was talking about an “issue” I found with the ExpandedControlText property which is now called DetailsExpandedLabel. This bug still exists even if it was logged here. Aside from this little issue, the new dialog can do great things.
I think that together, the examples you will find in my demo application and the one provided in the Samples/TaskDialogDemo folder of the WindowsAPICodePack will give you a good feel of what this dialog will let you achieve. Instead of recopying my previous article, I invite you to check the “The Command Link” and the “The Task Dialog” sections of my previous article.
Figure 2: The TaskDialog
Power Management feature
If you have users using laptops and if your applications are something doing resources intensive operations, you might consider not doing those operations when the laptop is running on batteries or when it is low on battery.
Figure 3: The Power management part
As you can see from the figure 3, the laptop on which I am writing this article is currently running on AC (otherwise, it would be written Battery). You also see that the battery is currently full. This is the kind of information that the power management feature of the Windows API Code pack gives you (and much more).
For example, the code required to fill the label you see in figure 3, is only 4 lines of code:
Private Sub PowerEvents(ByVal sender As Object, ByVal e As EventArgs)
lblPowerManagement.Text = PowerManager.PowerSource.ToString()
If PowerManager.IsBatteryPresent Then
lblPowerManagement.Text += ", Battery life = " + PowerManager.BatteryLifePercent.ToString + "%"
The PowerSource property of the PowerManager class returns the AC value (or Battery or even UPS). The IsBatteryPresent property indicates that you have a laptop and that you can query the BatteryLifePercent property.
You can also subscribe to events raised by the PowerManager class to monitor some events like the PowerSourceChanged and/or the BatteryLifePercentChanged as shown here:
' Adds event handlers for PowerManager events.
Private Sub CapturePowerManagementEvents()
AddHandler PowerManager.PowerSourceChanged, AddressOf PowerEvents
If PowerManager.IsBatteryPresent Then
AddHandler PowerManager.BatteryLifePercentChanged, AddressOf PowerEvents
This sample only refreshes the label control previously filled but you can imagine a much more complex scenario where you shut down the application when the battery life falls under a particular percentage.
The last I want to show you how easy it is to do is to prevent some action depending on those properties. For example, in my sample, I wouldn’t launch a particular action when the laptop is running on batteries. This is as simple as doing this:
' If running on battery, don't start the fake task
If PowerManager.PowerSource <> PowerSource.Battery Then
MessageBox.Show("Now starting a long, resources intensive ... fake job!", _
MessageBox.Show("Cannot do this task while running on batteries!", _
Application Restart and Recovery
This is another great feature of the Windows API Code pack. It is also one that was existing in the Vista Bridge and that I have explained in my previous article on that topic so I won’t totally repeat myself. This feature will help you recover gracefully after your application crashed.
If you want to learn more about this feature, please read my article the “The Application Restart and Recovery” section from my previous article as everything. The code of this article has been updated and is available into this month downloadable zip file. Once again, they changed some namespace and members’ name. But it works just as it used to be in the Vista Bridge so all the explanations are still valid.
I also strongly suggest you to open the sample provided by Microsoft from the Samples\AppRestartRecoveryDemo folder because it contains a real nice demo (shown in figure 4).
Figure 4: Make this app crash!
First, to be able to test this feature, you need to run the application itself and not from within Visual Studio otherwise the debugger will prevent you from recovering correctly.
Second, you need to wait for at least 60 seconds before crashing the application. This is a simple protection to prevent your application to crash when it starts, and then crash again, and then restart, and then ... you understand the pattern here?
Without a doubt, there are some really cool features in that package that we have explored here. My concern for corporate applications is that Windows 7 won’t be deployed on all PCs of my various clients’ sites on October 23rd! My other concern is that all my clients haven’t made the switch to VS2008 SP1 yet! And I am sure I am not alone in this situation!
Next month, I will continue to explore the Windows API Code Pack features that are specific to Windows 7 like the taskbar, the jump list, and the thumbnails.
I hope you appreciated the topic and see you next month.