Derek Lakin

Detecting Zune Connection for PhotoChooserTask

When you’re using the PhotoChooserTask to get the user to select or take a photo you may have experienced the problem when the user is connected to Zune because this prevents them from accessing their media library. Unfortunately, from a development point of view, the Complete event that fires simply provides Cancel as the Result, which is the same result for when the user simply presses the back button.

I’ve seen a few solutions to this problem; one was a timer based hack, one was a complicated solution regarding checking network interface types, and yet another tried to access the MediaLibrary and trap the resulting exception. I think these are relatively old solutions (taking into account that Windows Phone isn’t much over a year old!) and I flat out refused to use the timing hack, the network interface type solution didn’t work because it relied on reporting Ethernet when connected but I was getting None, and the final solution failed to throw the expected exception!

Fortunately, after some more investigation I stumbled across the solution. Not only does the Complete event give a result of Cancel, but the Error property is an InvalidOperationException, which gave me the following solution:

private void PhotoChooser_Complete(object sender, PhotoResult e)
{
    if ((TaskResult.Cancel == e.TaskResult) && (e.Error is InvalidOperationException))
    {
        // Zune software connected.
        MessageBox.Show(
            "Your phone is connected to the Zune software and cannot select a photo. Close the Zune software or disconnect your phone and try again.",
            "Zune Connected",
            MessageBoxButton.OK);
    }
    else if (TaskResult.OK == e.TaskResult)
    {
        // Carry on as usual. 
    }
}

NOTE: I actually use a toast-style notification here instead of a message box, but that’s a whole other post :)

media tasks wp7 wpdev applications