Archive for December, 2008

Programmatically changing the Device Name

Monday, December 15th, 2008

Screenshot of Set Device Name applicationFor some Line of Business (LOB) applications intended for tightly controlled deployment environments you may want to programatically set the Device Name of each PDA. This blog post discusses one common technique for achieving this.

Changing the Device Name

A Windows Mobile device stores the Device Name in the registry underneath the HKEY_LOCAL_MACHINE\Ident\Name value. This means we can make use of the Microsoft.Win32.Registry class to change the value and hence update the device name.

A code snippet for achieving this could take the following form.

using Microsoft.Win32;
void SetDeviceName(string deviceName)
  // Change the device name of the current Windows Mobile device
  using (RegistryKey key = Registry.LocalMachine.OpenSubkey("Ident", true))
    key.SetValue("Name", deviceName);

Verifying the change

The device’s TCP/IP stack utilises the device name as the device’s hostname. So an easy way to verify that the change has been successfully made is to ask what the current hostname is. This process is demonstrated below.

// Determine the current host name
using System.Net;
MessageBox.Show(Dns.GetHostName(), "Current Device Name");

Be aware however that certain parts of the operating system may require additional steps to be taken in order for them to read the updated information stored in the registry. Refer to the article titled “Naming a Device” available on MSDN for additional guidance.

Sample Application

[Download - 9.64 KB]

A small sample application is available for download. It demonstrates setting the device name programatically and includes two buttons to enable the user to verify that the change has been correctly made.

The first button asks the DNS subsystem for the current host name, while the second makes use of a technique discussed previously to display the Device ID control panel applet.

Another way to verify the change has been made is to simply connect the PDA to your desktop PC via ActiveSync. The main ActiveSync window displayed on the PC should display the device name in the top left hand corner.

30 Days of Windows Mobile – Day 08: Rotate Me

Sunday, December 14th, 2008

Rotate Me iconRotate Me is a simple application which demonstrates how to programmatically rotate the screen of a Windows Mobile device.

As discussed previously dynamic screen orientation changes was first introduced in Pocket PC 2003 Second Edition. There are four orientations understood by the operating system as shown below (I have also listed their typical orientations on a 240×320 QVGA device).

  • DMDO_0 – 0 degrees (portrait)
  • DMDO_90 – 90 degrees (landscape)
  • DMDO_180 – 180 degrees (upside down portrait)
  • DMDO_270 – 270 degrees (upside down landscape)

Determining the current screen orientation

The ChangeDisplaySettingsEx API acts a little like a catch all kitchen sink. It can be used to query and set the current state of various display related properties.

In order to query the current state of a property you pass in the CDS_TEST flag and specify the field(s) you want to query in the dmFields bitmask, as shown below.

static DWORD GetScreenOrientation()
  DEVMODE deviceMode;
  memset(&deviceMode, 0, sizeof(deviceMode));
  deviceMode.dmSize = sizeof(deviceMode);
  deviceMode.dmFields = DM_DISPLAYORIENTATION;
  // Query the DM_DISPLAYORIENTATION property
  if (ChangeDisplaySettingsEx(NULL, &deviceMode,
    return deviceMode.dmDisplayOrientation;
    return DMDO_DEFAULT;

Notice in this example we default to returning DMDO_DEFAULT (which is defined as DMDO_0) if the query fails. This seemed like a sensible default value to assume in the case of an error.

Changing the current screen orientation

To change the value of a display property we use a very similar code snippet, except we use the CDS_RESET flag and pre-populate the field in the DEVMODE structure with the desired value.

static void SetScreenOrientation(DWORD dwOrientation)
  DEVMODE deviceMode;
  memset(&deviceMode, 0, sizeof(deviceMode));
  deviceMode.dmSize = sizeof(deviceMode);
  deviceMode.dmFields = DM_DISPLAYORIENTATION;
  deviceMode.dmDisplayOrientation = dwOrientation;
  // Set the DM_DISPLAYORIENTATION property to the
  // specified orientation
  ChangeDisplaySettingsEx(NULL, &deviceMode,

Sample Application

[Download - 20.8 KB]

The small sample application available for download demonstrates using the above functions to change the screen orientation. Each time you run the application it will toggle the screen between 0 and 90 degrees rotation and then promptly quit. There is not even any user interface!

30 Days of Windows Mobile – Day 07: Mobile FX

Saturday, December 13th, 2008

Screenshot of Mobile FX ApplicationMobile FX is a fun sound effects engine for Windows Mobile. It displays a series of graphical buttons which clicked produce different sound effects. The user interface is driven by an XML based configuration file that enables the user to change which sound effects are available.

This is the 7th application in the 30 days of Windows Mobile series and marks my current re-commitment to progress in converting the number of applications currently sitting on my harddrive into blog posts. My hat is off to Chris Craft who managed 30 applications in 30 days. Although I took a similar amount of time to convert his C# applications into C++, it is taking me a lot longer to write the associated blog posts…

Mobile FX is an interesting application, in order to develop it in native code we will need to cover a number of new technologies and APIs which we have not covered before.

Creating controls at runtime

Up until now all of our applications have statically placed controls within the user interface via a dialog resource located in a *.rc resource file.

This application however specifies a variable number of sound effects within an XML based configuration file. Since the number of button controls required could change, it is easier to create the controls dynamically at runtime. The CreateWindow API enables us to create a control at runtime as shown below

// Create a static (label) control at runtime
HWND hWndPicture = CreateWindow(_T("static"),
  left, top, width, height,
  hDlg, NULL,

The first string parameter to CreateWindow specifies the type of control to create. A future blog post will discuss how to register your own custom controls so that they can be created via CreateWindow. The other parameters specify various properties related to the new control, such as its style, location and size.

If we want to make use of the GetDlgItem function to reference the newly created control we need to associate an ID with it. One way to do this is to use the SetWindowLong function as demonstrated below:

// Associate the id '1234' with the control 'hWnd'
SetWindowLong(hWnd, GWL_ID, 1234);

Turning relative paths into full paths

Most file based APIs within Windows CE require absolute file paths which start at the root of the filesystem (i.e. we must specify “\path\to\some\file.txt” instead of “file.txt”).

If we want to use relative file paths within our application we must manually convert them into absolute paths before passing them to system APIs. The OS provides no concept of a current working directory.

To convert a path specified relative to the directory the application is installed in we can make use of the following helper routine.

void GetFullPathToFile(LPTSTR pszFullPath, LPCTSTR pszFilename)
  // Find the path to the current executable
    pszFullPath, MAX_PATH);
  // Strip off the exe filename and replace it with
  // the path provided by our second parameter.
  wcscpy(wcsrchr(pszFullPath, '\\') + 1, pszFilename);

The trick is to use the GetModuleHandle and GetModuleFileName APIs to determine the path of the current executable. Once this is found we can use string manipulation functions to remove the *.exe file name and replace it with the name of the file we expect to find in the same folder.

An example use of the function is shown below.

// Place the absolute path to "test.wav" into szPath
GetFullPathToFile(szPath, L"test.wav");

Playing sounds

Instead of using the SndPlaySync API I decided to use an older API called PlaySound. Unlike SndPlaySync the PlaySound API is available on devices prior to Windows Mobile 6, the disadvantage however is that it only supports *.wav files (refer to my blog post about “Making use of new APIs within older applications” for one technique to support the use of new APIs while still allowing limited functionality on older devices).

To play a sound effect we simply pass the full path to the required *.wav file to PlaySound along with a couple of flags.

// Start to asyncronously play a sound
LPCTSTR pszSoundEffect = _T("\\path\\to\\some.wav");
PlaySound(pszSoundEffect, NULL,

This code snippet makes use of the SND_ASYNC flag. This means that the call to PlaySound does not block until the sound effect finishes playing. Instead the call returns immediately and the sound effect plays in the background.

Playing the sound effects asynchronously enables the user to interrupt the currently playing sound by selecting another sound effect. To stop any currently playing sound effects you can pass in NULL for the sound effect filename.

// Stop any currently playing sounds

Using Common Object Model (COM) objects

The early origins of the .NET runtime can be traced to the older COM and COM+ frameworks. As an example of this the commonly referenced mscorlib assembly at one stage stood for “Microsoft COM Object Runtime (COR) library“.

The Common Object Model (COM) framework can be considered to have many of the same design goals as the Common Language Runtime (CLR), such as the ability for objects written in various languages to interoperate with each other. The first step of using COM objects within an application is to initialise the framework by calling the CoInitializeEx API.

// Initilise the COM framework

Once we have initialised the COM runtime we can request objects to be created by calling the CoCreateInstance API, passing in the class id (CLSID) of the specific class we want to create an instance of. A CLSID is a unique GUID value which uniquely identifies a class. It enables the COM framework to lookup the registry to find details about how and where the class is implemented.

// Create an instance of the 'AAA" class and return a pointer
// to the newly created object in the pThingy variable
IAAA *pThingy = NULL;
  IID_IAAA, (void**)&pThingy);
  // ... use the object ...
// Release our reference to the object

Unlike the CLR framework the COM framework does not implement garbage collection, instead it is a reference counted API. Each object has a counter associated with it. Whenever an object is passed to another section of code its reference counter should be increased via a call to the AddRef method. Likewise when a section of code finishes using an object it should decrement the reference counter by calling the Release method. If Release causes the reference counter to decrease to zero the object’s resources are automatically freed. AddRef and Release are both part of an interface called IUnknown.

Drawing PNGs

Previous applications in this series have utilised Windows Bitmap (*.bmp) formatted images. This application is different since the application includes PNG formatted images to display on the sound effect buttons.

Prior to Windows Mobile 5.0 there was no general purpose API to manipulate images compressed in common image formats such as JPEGs, PNGs or GIFs (although there were options such as SHLoadImageFile). Windows Mobile 5.0 introduced a COM based Imaging API that offers a large number of image codecs as well as image manipulation functionality.

One benefit of using this API with PNG files is the ability for it to keep alpha transparency information in order to draw non rectangular images over top of existing content. The following subroutine can be used to draw a PNG onto an existing GDI device context.

// Draw an alpha blended image on the device context 'hdc'
// within the rectangle defined by 'prcBounds'.
static BOOL DrawAlphaImage(HDC hDC, RECT * prcBounds,
                           WCHAR * pszImageFileName)
  // Create an instance of the ImagingFactory class
  IImagingFactory *pFactory = NULL;
  HRESULT hr = CoCreateInstance(CLSID_ImagingFactory, NULL,
      CLSCTX_INPROC_SERVER, IID_IImagingFactory, (void**)&pFactory);
  if (hr == S_OK)
    // Call the CreateImageFromFile method to load the image
    // into memory.
    IImage *pImage = NULL;
    hr = pFactory->CreateImageFromFile(pszImageFileName, &pImage);
    if (hr == S_OK)
      // And finally draw the image onto the device context
      hr = pImage->Draw(hDC, prcBounds, NULL);
      // Free the COM objects
      pImage = NULL;
    pFactory = NULL;
  return (hr == S_OK);

Parsing XML

This is the first application that has required the parsing of an XML document. For this we can use another COM based API, the Microsoft (MSXML) DOM Parser. The first step is to create an instance of the DOM Document class.

// Create an instance of the XML Document class
IXMLDOMDocument *pDoc = NULL;
HRESULT hr = CoCreateInstance(CLSID_DOMDocument, NULL,
  CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pDoc);
if (hr == S_OK)
  // ... use the DOM document ...

Once we have an instance of the DOM document we can load an XML document into it by specifying the path to the XML file.

// Load the XML file
VARIANT filename;
V_BSTR(&filename) = SysAllocString(L"\\path\\to\\doc.xml");
V_VT(&filename) = VT_BSTR;
hr = pDoc->load(filename, &bSuccess);
if (hr == S_OK && bSuccess == VARIANT_TRUE)
  // ... make use of the document ...

There is a small amount of complexity here due to the load method making use of the VARIANT datatype (essentially a strongly typed container which can hold data of various datatypes).

Once we have loaded the XML document into memory we can query against it in a number of ways, including selecting a set of nodes via an XPATH expression.

IXMLDOMNodeList *pNodes = NULL;
LONG len = 0;
BSTR xpath = SysAllocString(L"/MobileFX/SoundPack/Buttons");
// Execute an XPATH query to obtain the set of nodes
// which match the predicate
if (pDoc->selectNodes(xpath, &pNodes) == S_OK
  && pNodes->get_length(&len) == S_OK)
  // Then iterate over each of the nodes
  // returned
  for (LONG i = 0; i < len; i++)
    // Fetch the next node
    IXMLDOMNode *pNode = NULL;
    if (pNodes->get_item(i, &pNode) == S_OK)
      // ... process the node ...

Reading the contents of the XML configuration file enables us to glue together a number of the code snippets shown previously. For each button found in the XML document we can dynamically create a button control, draw the PNG based icon onto it and load the sound effect specified by a relative path.

Sample Project

[Download - 2.34 MB]

The sample application available for download can be a lot of fun. However there are a couple of activities left as exercises for the interested developer. These would make great learning experiences, for example:

  • Add a menu item that allows the user to switch between multiple sound pack XML configuration files.
  • Add scrolling so a sound pack XML configuration file with more than 16 sound effects can be scrolled through to access additional sound effects.
  • Modify the CreateTile function so the sound effect images do not need to be “pre-buttonized”? The round edges and glossy finish should be able to be applied over top of a standard rectangular image by making multiple calls to the DrawAlphaImage function. Take a look at a tool such as Axialis IconWorkshop for some inspiration, and if you have a copy of Visual Studio 2008 you can download a special version for free! The iPhone does a similar thing for application and website shortcut icons.

Making a CAB file which doesn’t prompt for installation location

Thursday, December 11th, 2008

Screenshot showing application being installed on a Windows Mobile deviceWhen developing bespoke line of business applications it is common for your solution to require some form of hard reset recovery.

A common technique for implementing this is to package the application as a CAB file and then use a device specific technique to ensure that this file survives and automatically installs after a hard reset.

One problem you may come across in implementing this scenario is that a Smart Device CAB project created by Visual Studio will by default prompt the user to select where to install the application if one or more storage cards are present. This blog post covers one technique to remove this prompt when you want to reduce user interaction and need to hard-code the installation location of your application.

Finding an explanation

The first step towards finding a solution is to determine the reason why we are seeing the current behaviour. We can find an answer within the User Selected Installation section of the CAB Wizard documentation available on MSDN. This document states the following:

The user is prompted for the preferred installation volume only if the following two conditions are met:

  1. The application developer has created an %installdir% variable in the [CEStrings] section of the .inf file.
  2. The device has more than one storage volume available (such as a secondary MultiMedia card storage).

We obviously can not control the number of storage volumes present on a user’s device, but what is an *.inf file and how can we control the content of it’s [CEStrings] section?

Manually rebuilding a CAB file

The Smart Device CAB project type within Visual Studio is a simple GUI front end to a command line utility called CAB Wizard (cabwiz). When Visual Studio builds your project it takes the settings you have specified and behind the scenes generates a specially formatted text file (an *.inf file) which instructs the command line utility how to create your application’s CAB file.

Unfortunately for us the Visual Studio IDE always includes an %installdir% variable within the [CEStrings] section of the file it generates and there is no option that allows us to override this behaviour.

One possible work around to remove this variable is to allow Visual Studio to generate it’s *.inf file and then manually edit it and re-run the cabwiz utility by hand.

First we need to determine where the *.inf file is stored and the proper command line required to execute cabwiz.exe. This information can easily be found by looking at the Output Window of Visual Studio after you build your solution. Near the end of the log you should see a section that looks similar to the following:

------ Build started: Project: BespokeLOBApplicationCAB, Configuration: Debug ------
Building file 'C:\'...
"C:\Program Files\Microsoft Visual Studio 9.0\smartdevices\sdk\sdktools\cabwiz.exe"
    /dest "C:\Project\"
    /err CabWiz.log
Windows CE CAB Wizard

If you open the inf file specified in the above command line you should be able to find and then delete a line declaring the %installdir% variable (as highlighted in the screenshot below).

Screenshot showing the line which needs removed from the CAB's *.INF file

Once you have saved this change the last step is to open a MSDOS command prompt window and execute the command line discovered above to re-generate your CAB file. This new CAB file won’t prompt for an installation directory due to the lack of the %installdir% variable.

One thing to be aware of is that removing the %installdir% variable means placing files in the “Application Folder” directory within the File System Editor window will cause an error when you run cabwiz. Instead you should build up your directory structure by hand by right clicking in the file system editor and selecting the option to add new Custom Folders.

Sample Application

[Download - 18.1KB]

A small sample application is available for download which demonstrates this technique. A “dummy” application called BespokeLOBApplication is packaged into a CAB file via a Smart Device CAB project.

Notice if you build the CAB via the Visual Studio interface that the user will be prompted to select an installation location even though every file specified in the filesystem editor is deployed to a hard-coded location.

If you then alter the CAB file using the technique outlined above the user will not be prompted to select an installation location during installation.

For your convenience the download also contains two pre-built cab files called and to demonstrate the principal.

One disadvantage of this technique is that manual edits to the *.inf file will be lost the next time you rebuild your project via Visual Studio. If the structure of your CAB file does not change that often one solution is to remove the Smart Device CAB project from your solution and instead build your CAB file by executing the command line discovered above via a custom Post Build step.