问题
I've been working on a Windows Phone 7 app for a few months now and have a collection of useful detection flags that are used to test for things like if the code is running in the emulator, on a background/foreground thread, or at design time. (see full list here)
I now want to add a new flag that will check if the phone is connected to a desktop using a USB cable to prevent issues that users are reporting. There are certain operations that are blocked while the phone is connected to the Zune software, for example you cannot use the camera (it will just open and then immediately close with e.TaskResult == Microsoft.Phone.Tasks.TaskResult.Cancel). This causes my app to think that the user canceled the photo, which the user miss-interprets as the app not working correctly.
I'd like to detect when the phone is connected to the Zune software and provide a message saying the camera will not work until they disconnect it. Is there any way to do this?
回答1:
Gabor Dolhai has a full blog post on Zune Detection and Network Awareness, which uses a combiantion of NetworkInterfaceType detection and the NetworkAddressChangeed event.
回答2:
Testing for NetworkInterfaceType being Ethernet gets you close, but not quite there - as this isn't sensitive to the status of Zune vs WPConnect for the connection. Also, reading NetworkInterfaceType also can prove to be less than a walk in the park.
Handling the resulting exception seems to be the reliable method, however the exception does appear to vary between some media APIs, so keep an eye out for that.
回答3:
After reviewing the answers from Mike and Derek, I Decided to go with a simple timer to detect when the CameraCaptureTask
returns faster than expected. This is done by adding the following right before the call to start the capture task:
State["CameraCaptureStart"] = DateTime.Now;//Save start time to detect fast cancel from zune software
Then when the capture finishes you can detect if it returned too fast:
//Detect if task returned too fast
if (State.ContainsKey("CameraCaptureStart"))
{
DateTime dtStart = (DateTime)State["CameraCaptureStart"];
TimeSpan ts = DateTime.Now - dtStart;
if (ts < TimeSpan.FromSeconds(3))
{
MessageBox.Show("Error: Camera does not work while phone is connected to the Zune software.");
}
}
In my testing the fastest I could load the camera, take a picure, and push the accept button was around 5-6 seconds, where as the Zune software would automatic cancel and return in around 2.5 seconds.
This approach is simple and works well for my situation, however you should be aware that the error message will also be displayed if the user presses the back button before the 3 second timeout has elapsed.
来源:https://stackoverflow.com/questions/4744399/detect-if-windows-phone-7-is-connected-to-desktop-zune-software