How to use Hardware based Compass in Windows Phone 7 without Compass API
Microsoft hasn't provided API for accessing compass present in Windows Phone 7 device. For this reason getting compass value is difficult (not impossible, describing below) on smartphones running Windows Phone 7. Fortunately, HTC released HTC Compass application few days back at Windows Phone Marketplace, that application uses an obscure way of accessing compass hardware from HTC Phone. Since I'm working on an application called ThirdEye along with my team Team Rapture, where compass is very much necessary, we were hunting the internet for any solution if the compass is possible to be accessed thought API is not present at this period of time. Finally, I succeed. Here are the steps I followed to get the value of compass in Windows Phone 7. I tested the code in HTC HD7 and it worked fine.
The blog was first posted on my Blogspot site, it has been copied here for archiving purpose. Some links might not work, and the solution is obsolete now
In HTC Compass Application, HTC used unmanaged COM library (DigiCompassCOM.dll
and ComRegRW_Compass.dll
) to get value from compass. I got those two files from the .xap
file. And to use unmanaged .dll
file in your Windows Phone 7 application you need to use the hidden Microsoft.Phone.InteropServices.dll
file in Windows Phone 7 device which I collected from the internet. As because visual studio doesn't allow you to directly add reference to the Microsoft.Phone.InteropServices.dll
file, I had to use Reflection to invoke methods inside that DLL (Thanks for my friend, team member Shishir for helping regarding this). Not wasting any time, here are the complete C# source code of my DigitalCompassService
class.
Note that, you have to include all two dll files and Microsoft.Phone.InteropServices.dll
file in the Windows Phone 7 Application project. and you can not test this code in Emulator, a COM Exception will occur, deploy the code in phone, it works!!
Download all DLL files with complete source code here
please remember that, as these type of technique might not be considered legal, so please don't use this code in your commercial application. lets hope, Microsoft adds Compass API in Windows Phone 7 SDK soon.
If you face any problem please reply to this post.