How to programatically turn Bluetooth ON and OFF in Rhodium - Windows Mobile Development and Hacking General

I cannot get BT toggled in Rhodium using the usual method for Widcomm/Broadcom:
Code:
HWND bt_hwnd = FindWindow(L"WCE_BTTRAY", 0);
UINT COMMANDGET = RegisterWindowMessage(L"WIDCOMM_WM_GETSTACKSTATUS");
DWORD resultget = SendMessage(bt_hwnd, COMMANDGET, 0, 0);
UINT COMMAND;
if(resultget > 0)
COMMAND = RegisterWindowMessage(L"WIDCOMM_WM_BTRADIO_ON");
else
COMMAND = RegisterWindowMessage(L"WIDCOMM_WM_BTRADIO_OFF");
resultset = SendMessage(bt_hwnd, COMMAND, 0, 0);
I've seen that the new Broadcom stack has many more messages, but cannot figure how to use them for turning BT ON and OFF. Does anybody know how to do this?
Code:
WIDCOMM_WM_STACK_LOAD
WIDCOMM_WM_STACK_UNLOAD
WIDCOMM_WM_GETSTACKSTATUS
WIDCOMM_WM_SETSTACKCONFIG
WIDCOMM_WM_BTRADIO_OFF
WIDCOMM_WM_BTRADIO_ON
WIDCOMM_WM_VISIBLE1
WIDCOMM_WM_REG_PROF_NOTIF
WIDCOMM_WM_REG_PROF_EVENT
WIDCOMM_WM_ACTIVESYNC
WIDCOMM_WM_ISVISIBILITYTIMER
WIDCOMM_WM_IDENT_CHANGE
WIDCOMM_WM_POST_STACK_LOAD
WIDCOMM_WM_UPDATE_STATUS
WIDCOMM_WM_KILL_VISIBILITYTIMER
WIDCOMM_WM_SET_FM_CONFIG
WIDCOMM_WM_PROF_CHANGE_EVENT
WIDCOMM_WM_STACKLOADED
WIDCOMM_WM_STACKUNLOADED
WIDCOMM_WM_TRAYUNLOADED
WIDCOMM_WM_ACTIVATE

beemerTPPC said:
I cannot get BT toggled in Rhodium using the usual method for Widcomm/Broadcom...
Click to expand...
Click to collapse
From what I've found on the web, you can't toggle anymore. The function calls are still implemented but the have no effect.
For beeing able to turn BT off / on, the procedure (afair) is:
- unload stack
- set registry entry
- load stack
I simply even didn't find out how to unload the stack programmatically, so I gave up for the moment.
However, you might be able to figure out by debugging the function the commmgr is using. Just an idea.
cheers

can't you just use 32Feet? BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable

grzegorzaksamit said:
can't you just use 32Feet? BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable
Click to expand...
Click to collapse
Broadcom stack is not supported by 32feet.
EDIT:
According to this info it's supported now
http://32feet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28849

Not sure if this at all still relevant, but to me it was today. I loaded up IDA on CommManager and it turned out very simple:
#include <windows.h>
#include <BtSdkCE.h>
Code:
int main(int argc, char* argv[]) {
HWND bt_hwnd = FindWindow(L"WCE_BTTRAY", 0);
int WIDCOMM_WM_GETSTACKSTATUS = RegisterWindowMessage(L"WIDCOMM_WM_GETSTACKSTATUS");
DWORD radio_enabled = SendMessage(bt_hwnd, WIDCOMM_WM_GETSTACKSTATUS, 0, 0);
UINT WIDCOMM_WM_SETSTACKCONFIG = RegisterWindowMessage(L"WIDCOMM_WM_SETSTACKCONFIG");
if (!radio_enabled)
SendMessage(bt_hwnd, WIDCOMM_WM_SETSTACKCONFIG, 1, 1);
else
SendMessage(bt_hwnd, WIDCOMM_WM_SETSTACKCONFIG, 0, 0);
return 0;
}
I tested this on 4 different widcomm stack carrying device (rhodium, leo, hp214, hp hx4100) and it seems to work fine. Hopefully this will save someone a bit of time, as it took my quite a while to figure it out, but then again I'm not really used to reverse engineering.

works it too for the wizard

No idea, afaik wizard uses microsoft stack so it's not an issue anyway. I do believe u can use the widcomm stack on the wizard, in that case this would work.

bluetooth toggler
try this the attached zip file. unzip and copy to your device in \windows\start menu\programs

vanilaguy said:
try this the attached zip file. unzip and copy to your device in \windows\start menu\programs
Click to expand...
Click to collapse
old bluetooth switcher wont work with Leo

executable
Figured I might as well compile it. Should work on every widcomm enabled stack.
Also added a managed C# class to enable and disable radios on both microsoft and widcomm stack enabled devices. Creating a native one for both stacks shouldn't be hard either, but I have no need for it at all, so I didn't.
Code:
public static class BthRadio {
/// <summary>
/// Whether the device is equipped with a Widcomm bluetooth stack
/// </summary>
public static bool IsWidcomm;
/// <summary>
/// Whether the device is equipped with a Microsoft bluetooth stack
/// </summary>
public static bool IsMicrosoft;
/// <summary>
/// Determines stack properties
/// </summary>
static BthRadio() {
// determine stack type used on this device
IsWidcomm = OpenNETCF.NativeMethods.NativeLibraryExists("BtSdkCE50.dll") ||
OpenNETCF.NativeMethods.NativeLibraryExists("BtSdkCE30.dll");
IsMicrosoft = !IsWidcomm;
}
/// <summary>
/// Toggles bluetooth radio enabledness
/// </summary>
/// <returns>Whether the action was performed successfully</returns>
public static bool ToggleRadio() {
if (IsEnabled()) return DisableRadio();
else return EnableRadio();
}
/// <summary>
/// Returns whether primary radio is enabled
/// </summary>
/// <returns></returns>
public static bool IsEnabled() {
int mode = -1;
if (IsMicrosoft) {
int success = BthGetMode(ref mode);
return success == 0 && mode >= 1;
}
else {
IntPtr bt_hwnd = Win32.FindWindow("WCE_BTTRAY", null);
uint WIDCOMM_WM_GETSTACKSTATUS = Win32.RegisterWindowMessage("WIDCOMM_WM_GETSTACKSTATUS");
int radio_enabled = Win32.SendMessage(bt_hwnd, WIDCOMM_WM_GETSTACKSTATUS, 0, 0) & 1;
return radio_enabled != 0;
}
}
/// <summary>
/// Attempts to enable the bluetooth radio.
/// </summary>
/// <returns>True if operation executed successfully, otherwise false</returns>
public static bool EnableRadio() {
if (IsMicrosoft) return BthSetMode(1) == 0;
else {
uint WIDCOMM_WM_SETSTACKCONFIG = Win32.RegisterWindowMessage("WIDCOMM_WM_SETSTACKCONFIG");
int result = Win32.SendMessage(Win32.FindWindow("WCE_BTTRAY", null), WIDCOMM_WM_SETSTACKCONFIG, 1, 1);
if (result == 0) return false;
// sleep at least 3 seconds, required before change can take effect
Thread.Sleep(3000);
// now poll at most an additional 15 seconds to determine if the
// change was in fact effective
for (int i = 0; i < 15; i++) if (IsEnabled()) break;
return IsEnabled();
}
}
/// <summary>
/// Attempts to disable the bluetooth radio.
/// </summary>
/// <returns>True if operation executed successfully, otherwise false</returns>
public static bool DisableRadio() {
if (IsMicrosoft) return BthSetMode(0) == 0;
else {
uint WIDCOMM_WM_SETSTACKCONFIG = Win32.RegisterWindowMessage("WIDCOMM_WM_SETSTACKCONFIG");
int result = Win32.SendMessage(Win32.FindWindow("WCE_BTTRAY", null), WIDCOMM_WM_SETSTACKCONFIG, 0, 0);
if (result == 0) return false;
// sleep at least 3 seconds, required before change can take effect
Thread.Sleep(3000);
// now poll at most an additional 15 seconds to determine if the
// change was in fact effective
for (int i = 0; i < 15; i++) if (!IsEnabled()) break;
return !IsEnabled();
}
}
#region Bluetooth P/Invoke declarations
[DllImport("BthUtil.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int BthSetMode(int dwMode);
[DllImport("BthUtil.dll", CharSet = CharSet.Auto)]
public static extern int BthGetMode(ref int pdwMode);
#endregion
}

Wow, can you share the full code. I Just started developing and this is a bit to hard to implement for me

ajhvdb said:
Wow, can you share the full code. I Just started developing and this is a bit to hard to implement for me
Click to expand...
Click to collapse
I did, right? What did I omit?

"togglebth.exe" test report: work great with Leo
great skill!

zzattack said:
I did, right? What did I omit?
Click to expand...
Click to collapse
Wel i'm a starting developer... Could you share the project solution folder, including you function. This way I can debug/compile it.

ajhvdb said:
Wel i'm a starting developer... Could you share the project solution folder, including you function. This way I can debug/compile it.
Click to expand...
Click to collapse
Well sure I can do that, but it doesn't get any simpler than this. You'll need Visual Studio 2008, the broadcom SDK installed (and VS point to it's include/library files), and the Windows Mobile 5.0 SDK (or higher, I'd pick 6.0 and 6.5). Anyway, I attached the solution.

Thanks, and fast. I just wanted to see how you would use this class. (It's completely new to me).
Edit:
Just looked at it. So your communicating whit this WCE_BTTRAY program and depending on the answer do something.

ajhvdb said:
Thanks, and fast. I just wanted to see how you would use this class. (It's completely new to me).
Edit:
Just looked at it. So your communicating whit this WCE_BTTRAY program and depending on the answer do something.
Click to expand...
Click to collapse
This isn't much of a class, just a few lines of code :S
It just looks for the current status, if it's currently enabled it tries to disable the stack, if it's disabled it tries to enable it and that's it ;/

Related

Turn ON/OFF BT/Widcomm on BA with eVc

Does anyone know how to turn on and off the Widcomm bluetooth on a Blue Angel from within C/eVc? :?:
tia
The only official way to turn off the radio is to destroy the last of the BT objects using the stack (the stack is object orientated, creating an object turns it on, destroying the lst object turns it off, this assumes you have the widcomm SDK). The problem is that the BT app that runs in the system tray (and shows you that bluetooth icon in the bottom left) owns a stack object that you cant properly destroy, hence you can't turn the radio off.
hrm...
If the tray app wasn't running, theres a function in the wbtapiCE.dll called UnloadStack ([email protected]@@[email protected]@[email protected]) which should force the stack to unload and probably turn off the radio.
So we might be able to turn it OFF this way. And how do we turn in ON again ;-)
Theres a corrasponding LoadStack ([email protected]@@[email protected]@[email protected]) which would do the job.
Each of these accept two parameters, the first appears to be a pointer to a class, the second a numeric value.
For the class pointer, it appears that you can define an 8 byte array and call the constructor ( [email protected]@[email protected] ) on it, remember to call the destructor ( [email protected]@[email protected] ) when your done. The hex value appears to be 0x123456 for LoadStack and 0x654321 for UnloadStack.
I really don't know how successfull you would be starting the stack yourself, spinning up the BT tray app, then killing it and shutting down the stack, you may find you have to replace all the functionality of the tray app yourself.
Complicated stuff. I might be easier off doing FindWindow on the BtApp and find the ON and OFF buttons and programatically press them.
Hello All.
I call wbtapiCE.dll functions for on/off BT on dell axim x30.
I use, two dll metods
[email protected]@@[email protected]@[email protected] == public: enum WBtRc __cdecl CWBtAPI::UnloadStack(unsigned int)
and
>> [email protected]@@[email protected]@[email protected] == public: enum WBtRc __cdecl CWBtAPI::LoadStack(unsigned int)
But no positive effect.
Anybody know what i doing wrong?
Sample code below:
{
CString szDllPath = _T("wbtapiCE.dll");
HMODULE hMod = LoadLibrary(szDllPath);
if(hMod==NULL)
{
AfxMessageBox(_T("LoadLibrary Failed !!!"));
}
//__cdecl CWBtAPI::CWBtAPI(void)
typedef void (CWBtAPI::*PFNCreateCWBt)();
typedef void (CWBtAPI::*PFNDestructorOfCWBt)();
typedef int (CWBtAPI::*PFNLoadCWBt)(unsigned int);
typedef int (CWBtAPI::*PFNUnLoadCWBt)(unsigned int);
//>> >> [email protected]@@[email protected]@[email protected] == public: enum WBtRc __cdecl CWBtAPI::UnloadStack(unsigned int)
CWBtAPI* a1 = (CWBtAPI*)_alloca(sizeof(CWBtAPI));
PFNCreateCWBt pfnCreateWBt = force_cast<PFNCreateCWBt>(GetProcAddress(hMod, TEXT("[email protected]@[email protected]")));
(a1->*pfnCreateWBt)();
//////////////////////////////////////////////////////////////////////////
PFNUnLoadCWBt pfnUnLoadA = force_cast<PFNUnLoadCWBt>(GetProcAddress(hMod, TEXT("[email protected]@@[email protected]@[email protected]")));
AfxMessageBox(_T("Started pfnUnLoadA"));
int result = (a1->*pfnUnLoadA)( 0x654321);
CString err = _T("Done pfnUnLoadA");
AfxMessageBox(err );
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
PFNLoadCWBt pfnLoadA = force_cast<PFNLoadCWBt>(GetProcAddress(hMod, TEXT("[email protected]@@[email protected]@[email protected]")));
AfxMessageBox(_T("Started pfnLoadA"));
result = (a1->*pfnLoadA)(0x123456);
AfxMessageBox(_T("Done pfnLoadA"));
//////////////////////////////////////////////////////////////////////////
PFNDestructorOfCWBt pfnDestA = force_cast<PFNDestructorOfCWBt>(GetProcAddress(hMod, TEXT("[email protected]@[email protected]")));
(a1->*pfnDestA)();
/*************************************************************************/
FreeLibrary(hMod);
}
could some kind soul maybe write a script to do someth like that...
I make it BT on/off
Jn dell axim X30 exist btpwr.dll.
This dll export some interesting methods.
1 0 0000128C PowerDeInit
2 1 00001284 PowerInit
3 2 00001258 PowerOff
4 3 0000121C PowerOn
I call this methods directly from dll, and i turn on turn off bt !!
Sample code below:
void DoTrayOn()
{
CString szDllPath = _T("btpwr.dll");
HMODULE hMod = LoadLibrary(szDllPath);
if(hMod==NULL)
{
AfxMessageBox(_T("LoadLibrary Failed !!!"));
}
typedef int (*BTPowerOn)();
BTPowerOn bton = (BTPowerOn) GetProcAddress(hMod, TEXT("PowerOn"));
if (NULL != bton)
{
// AfxMessageBox(_T("Start DoTrayOn"));
(bton) ();
}else
{
// AfxMessageBox(_T("Error NULL DoTrayOn pointer"));
}
FreeLibrary(hMod);
}
void DoTrayOff()
{
CString szDllPath = _T("btpwr.dll");
HMODULE hMod = LoadLibrary(szDllPath);
if(hMod==NULL)
{
AfxMessageBox(_T("LoadLibrary Failed !!!"));
}
typedef int (*BTPowerOff)();
BTPowerOff bton = (BTPowerOff) GetProcAddress(hMod, TEXT("PowerOff"));
if (NULL != bton)
{
// AfxMessageBox(_T("Start DoTrayOn"));
(bton) ();
}else
{
// AfxMessageBox(_T("Error NULL DoTrayOn pointer"));
}
FreeLibrary(hMod);
}
Bluetooth turn on/turn off
Hello
Have you a solution for turn on and turn off bluetooth by code?
I have a widcomm stack and I use c# .net
i'm searching for a solution for my Touch Pro 2 with Widcomm BT Stack.
i can turn on BT by creating an object of CBtIf, but can't turn of BT by deleting the object.
someone has an idea?
regards
IceFire

Programmatically cycle sound icon (sound/vibrate/mute)

When you click on the sound icon, you get the two sliders and three radio buttons. Anyone know how to set those radio buttons through code (C++) so it gets reflected in the icon display (and actually changes the "profile")?. I'd like to change to vibrate/mute/sound at different times using something like alarmToday to run a small app.
Thanks,
sbl
I wrote a profiles app in .net and C++ here are some code snippets;
You can change the registry values for the volumes (I cant remember which as I wrote it a long time ago), then you need to call the following to have the values applied.
// ProfilesHelper.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "ProfilesHelper.h"
#include <windows.h>
#include <Soundfile.h>
void WINEXPORT SetSoundMode(int mode)
{
// Initialize an empty SNDFILEINFO structure
SNDFILEINFO sndfile = {0};
if (mode == 0)
sndfile.sstType = SND_SOUNDTYPE_ON;
if (mode == 1)
sndfile.sstType = SND_SOUNDTYPE_VIBRATE;
if (mode == 2)
sndfile.sstType = SND_SOUNDTYPE_NONE;
SndSetSound(SND_EVENT_ALL, &sndfile, false);
void AudioUpdateFromRegistry();
}
void WINEXPORT SetSystemVolume(long volume)
{
waveOutSetVolume(NULL, volume);
void AudioUpdateFromRegistry();
}
Hi,
I have a similar need of programatically cycling the sound icon to MUTE VIBRATE and normal volume icon. I can do it successfully on Windows Mobile 5.0. I created a sample application with Visual Studio 2005 for WM 5.0 and I am able to set the icons as i want. But when i tried it for PPC2003 I was not able to compile that. Missing SoudFile.h. Can any one help me to find out how to do the same thing on PPC2003 specifically i-mate devices like PDA2 and PDA2K.
Thanks
With Regards,
Bhagat Nirav K.
i know its a 2 ur old post..but i need help also now
how can i mute sounds using C# in .net 2.0 for WM6
Just forget about this header file...
Operate on HKCU\ControlPanel\Notifications\ShellOverrides\Mode value. It can have 3 states: 0 == normal, 1 == vibrate and 2 == silent. That's all
Probably you need to call AudioUpdateFromRegistry function from coredll.dll.
Or... another method
look at HKCU\ControlPanel\Sounds\RingTone0:Sound, it takes 3 different values:
*none*
*vibrate*
your ringtone name, taken from SavedSound value in the same key.
Hi,
Firstly I know this post is way old, but I thought of responding to it since I was stuck on this topic for a couple of days and couldnt find a way to resolve it.
Also others having this problem will also be redirected here through various search results as I was. So to aid them
1. Meddling with the registry to change the sound profiles didnt work for me. I tried Changing the Mode inHKCU\ControlPanel\Notifications\ShellOverrides\Mode but that didnt work on my phone.
2. What I currently have working is the following code - C# with Pinvoke
public enum SND_SOUNDTYPE
{
On,
File,
Vibrate,
None
}
private enum SND_EVENT
{
All,
RingLine1,
RingLine2,
KnownCallerLine1,
RoamingLine1,
RingVoip
}
[StructLayout(LayoutKind.Sequential)]
private struct SNDFILEINFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szPathName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
public SND_SOUNDTYPE sstType;
}
[DllImport("coredll.dll")]
public static extern void AudioUpdateFromRegistry ();
[DllImport("aygshell.dll", SetLastError = true)]
private static extern uint SndSetSound(SND_EVENT seSoundEvent, ref SNDFILEINFO pSoundFileInfo, bool fSuppressUI);
static void SetProfileNormal()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.On;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
static void SetProfileVibrate()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.Vibrate;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
static void SetProfileMuted()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.None;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
Hope this helps

GPS Intermediate Driver parsed API - in VB?

Is anyone currently using the GPS Intermediate Driver parsed API in VB?
I'm looking to get started but needing a bit of a kick-start. I've found the API to be used and it seems simple enough with only 4 functions but I don't see an example of anyone using it in VB, anywhere...
From the example in C++ from the SDK the DLL has the following functions but I don't know how to convert to VB, can anyone give a hand?
#region PInvokes to gpsapi.dll
[DllImport("gpsapi.dll")]
static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSCloseDevice(IntPtr hGPSDevice);
[DllImport("gpsapi.dll")]
static extern int GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, int dwMaximumAge, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSGetDeviceState(IntPtr pGPSDevice);
#endregion
Thanks,
can you post the c++ code here. we can try and rebuild the data structures for vb which would allow you to execute the dll functions. (I would od it but I'm at work, not access)
How much of the code are you interested in?
In case anyone is interested I was able to find an unwilling soul to convert the first signature.
Here is the signature in C#:
[DllImport("gpsapi.dll")]static extern IntPtr GPSOpenDevice( IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags);In VB, it looks like this:
In VB:
<DllImport("gpsapi.dll")> _Function Shared GPSOpenDevice( _ ByVal hNewLocationData As IntPtr, _ ByVal hDeviceStateChange As IntPtr, _ ByVal szDeviceName As String, _ ByVal dwFlags As Integer) As IntPtrEnd Function
hopefully some others can help come up with some simple VB source for using the GPS device....
I believe this is from a class module:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
namespace Microsoft.WindowsMobile.Samples.Location
{
public delegate void LocationChangedEventHandler(object sender, LocationChangedEventArgs args);
public delegate void DeviceStateChangedEventHandler(object sender, DeviceStateChangedEventArgs args);
/// <summary>
/// Summary description for GPS.
/// </summary>
public class Gps
{
// handle to the gps device
IntPtr gpsHandle = IntPtr.Zero;
// handle to the native event that is signalled when the GPS
// devices gets a new location
IntPtr newLocationHandle = IntPtr.Zero;
// handle to the native event that is signalled when the GPS
// device state changes
IntPtr deviceStateChangedHandle = IntPtr.Zero;
// handle to the native event that we use to stop our event
// thread
IntPtr stopHandle = IntPtr.Zero;
// holds our event thread instance
System.Threading.Thread gpsEventThread = null;
event LocationChangedEventHandler locationChanged;
/// <summary>
/// Event that is raised when the GPS locaction data changes
/// </summary>
public event LocationChangedEventHandler LocationChanged
{
add
{
locationChanged += value;
// create our event thread only if the user decides to listen
CreateGpsEventThread();
}
remove
{
locationChanged -= value;
}
}
event DeviceStateChangedEventHandler deviceStateChanged;
/// <summary>
/// Event that is raised when the GPS device state changes
/// </summary>
public event DeviceStateChangedEventHandler DeviceStateChanged
{
add
{
deviceStateChanged += value;
// create our event thread only if the user decides to listen
CreateGpsEventThread();
}
remove
{
deviceStateChanged -= value;
}
}
/// <summary>
/// True: The GPS device has been opened. False: It has not been opened
/// </summary>
public bool Opened
{
get { return gpsHandle != IntPtr.Zero; }
}
public Gps()
{
}
~Gps()
{
// make sure that the GPS was closed.
Close();
}
/// <summary>
/// Opens the GPS device and prepares to receive data from it.
/// </summary>
public void Open()
{
if (!Opened)
{
// create handles for GPS events
newLocationHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
deviceStateChangedHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
stopHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
gpsHandle = GPSOpenDevice(newLocationHandle, deviceStateChangedHandle, null, 0);
// if events were hooked up before the device was opened, we'll need
// to create the gps event thread.
if (locationChanged != null || deviceStateChanged != null)
{
CreateGpsEventThread();
}
}
}
/// <summary>
/// Closes the gps device.
/// </summary>
public void Close()
{
if (gpsHandle != IntPtr.Zero)
{
GPSCloseDevice(gpsHandle);
gpsHandle = IntPtr.Zero;
}
// Set our native stop event so we can exit our event thread.
if (stopHandle != IntPtr.Zero)
{
EventModify(stopHandle, eventSet);
}
// block until our event thread is finished before
// we close our native event handles
lock (this)
{
if (newLocationHandle != IntPtr.Zero)
{
CloseHandle(newLocationHandle);
newLocationHandle = IntPtr.Zero;
}
if (deviceStateChangedHandle != IntPtr.Zero)
{
CloseHandle(deviceStateChangedHandle);
deviceStateChangedHandle = IntPtr.Zero;
}
if (stopHandle != IntPtr.Zero)
{
CloseHandle(stopHandle);
stopHandle = IntPtr.Zero;
}
}
}
/// <summary>
/// Get the position reported by the GPS receiver
/// </summary>
/// <returns>GpsPosition class with all the position details</returns>
public GpsPosition GetPosition()
{
return GetPosition(TimeSpan.Zero);
}
/// <summary>
/// Get the position reported by the GPS receiver that is no older than
/// the maxAge passed in
/// </summary>
/// <param name="maxAge">Max age of the gps position data that you want back.
/// If there is no data within the required age, null is returned.
/// if maxAge == TimeSpan.Zero, then the age of the data is ignored</param>
/// <returns>GpsPosition class with all the position details</returns>
public GpsPosition GetPosition(TimeSpan maxAge)
{
GpsPosition gpsPosition = null;
if (Opened)
{
// allocate the necessary memory on the native side. We have a class (GpsPosition) that
// has the same memory layout as its native counterpart
IntPtr ptr = Utils.LocalAlloc(Marshal.SizeOf(typeof(GpsPosition)));
// fill in the required fields
gpsPosition = new GpsPosition();
gpsPosition.dwVersion = 1;
gpsPosition.dwSize = Marshal.SizeOf(typeof(GpsPosition));
// Marshal our data to the native pointer we allocated.
Marshal.StructureToPtr(gpsPosition, ptr, false);
// call native method passing in our native buffer
int result = GPSGetPosition(gpsHandle, ptr, 500000, 0);
if (result == 0)
{
// native call succeeded, marshal native data to our managed data
gpsPosition = (GpsPosition)Marshal.PtrToStructure(ptr, typeof(GpsPosition));
if (maxAge != TimeSpan.Zero)
{
// check to see if the data is recent enough.
if (!gpsPosition.TimeValid || DateTime.Now - maxAge > gpsPosition.Time)
{
gpsPosition = null;
}
}
}
// free our native memory
Utils.LocalFree(ptr);
}
return gpsPosition;
}
Sorry had to post the remaining source in another thread:
/// <summary>
/// Queries the device state.
/// </summary>
/// <returns>Device state information</returns>
public GpsDeviceState GetDeviceState()
{
GpsDeviceState device = null;
// allocate a buffer on the native side. Since the
IntPtr pGpsDevice = Utils.LocalAlloc(GpsDeviceState.GpsDeviceStructureSize);
// GPS_DEVICE structure has arrays of characters, it's easier to just
// write directly into memory rather than create a managed structure with
// the same layout.
Marshal.WriteInt32(pGpsDevice, 1); // write out GPS version of 1
Marshal.WriteInt32(pGpsDevice, 4, GpsDeviceState.GpsDeviceStructureSize); // write out dwSize of structure
int result = GPSGetDeviceState(pGpsDevice);
if (result == 0)
{
// instantiate the GpsDeviceState class passing in the native pointer
device = new GpsDeviceState(pGpsDevice);
}
// free our native memory
Utils.LocalFree(pGpsDevice);
return device;
}
/// <summary>
/// Creates our event thread that will receive native events
/// </summary>
private void CreateGpsEventThread()
{
// we only want to create the thread if we don't have one created already
// and we have opened the gps device
if (gpsEventThread == null && gpsHandle != IntPtr.Zero)
{
// Create and start thread to listen for GPS events
gpsEventThread = new System.Threading.Thread(new System.Threading.ThreadStart(WaitForGpsEvents));
gpsEventThread.Start();
}
}
/// <summary>
/// Method used to listen for native events from the GPS.
/// </summary>
private void WaitForGpsEvents()
{
lock (this)
{
bool listening = true;
// allocate 3 handles worth of memory to pass to WaitForMultipleObjects
IntPtr handles = Utils.LocalAlloc(12);
// write the three handles we are listening for.
Marshal.WriteInt32(handles, 0, stopHandle.ToInt32());
Marshal.WriteInt32(handles, 4, deviceStateChangedHandle.ToInt32());
Marshal.WriteInt32(handles, 8, newLocationHandle.ToInt32());
while (listening)
{
int obj = WaitForMultipleObjects(3, handles, 0, -1);
if (obj != waitFailed)
{
switch (obj)
{
case 0:
// we've been signalled to stop
listening = false;
break;
case 1:
// device state has changed
if (deviceStateChanged != null)
{
deviceStateChanged(this, new DeviceStateChangedEventArgs(GetDeviceState()));
}
break;
case 2:
// location has changed
if (locationChanged != null)
{
locationChanged(this, new LocationChangedEventArgs(GetPosition()));
}
break;
}
}
}
// free the memory we allocated for the native handles
Utils.LocalFree(handles);
// clear our gpsEventThread so that we can recreate this thread again
// if the events are hooked up again.
gpsEventThread = null;
}
}
#region PInvokes to gpsapi.dll
[DllImport("gpsapi.dll")]
static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSCloseDevice(IntPtr hGPSDevice);
[DllImport("gpsapi.dll")]
static extern int GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, int dwMaximumAge, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSGetDeviceState(IntPtr pGPSDevice);
#endregion
#region PInvokes to coredll.dll
[DllImport("coredll.dll")]
static extern IntPtr CreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, StringBuilder lpName);
[DllImport("coredll.dll")]
static extern int CloseHandle(IntPtr hObject);
const int waitFailed = -1;
[DllImport("coredll.dll")]
static extern int WaitForMultipleObjects(int nCount, IntPtr lpHandles, int fWaitAll, int dwMilliseconds);
const int eventSet = 3;
[DllImport("coredll.dll")]
static extern int EventModify(IntPtr hHandle, int dwFunc);
#endregion
}
}
Well I've made a little progress but once again I'm stumped since I don't program in C..
Currently I'm able to open and close the GPS device on my phone but in order to retrieve information I believe I need a stuct converted to VB. I'm not familiar with struct so I'm hoping someone can explain it to me and or maybe help convert it.
These are the functions that have been converted to VB from C:
'Put this at the top of your module.
'Required in all cases when calling API functions
Imports System.Runtime.InteropServices
'Required in this example and any API function which
'use a string buffer. Provides the StringBuilder class
Imports System.Text
Public Class Form1
<DllImport("gpsapi.dll", EntryPoint:="GPSOpenDevice", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSOpenDevice(ByVal hNewLocationData As IntPtr, ByVal hDeviceStateChange As IntPtr, ByVal szDeviceName As String, ByVal dwFlags As Integer) As IntPtr
End Function
<DllImport("gpsapi.dll", EntryPoint:="GPSCloseDevice", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSCloseDevice(ByVal hGPSDevice As IntPtr) As Integer
End Function
<DllImport("gpsapi.dll", EntryPoint:="GPSGetPosition", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSGetPosition(ByVal hGPSDevice As IntPtr, ByVal pGPSPosition As IntPtr, ByVal dwMaximumAge As Integer, ByVal dwFlags As Integer) As Integer
End Function
<DllImport("gpsapi.dll", EntryPoint:="GPSGetDeviceState", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSGetDeviceState(ByVal pGPSDevice As IntPtr) As Integer
End Function
Click to expand...
Click to collapse
and this is the struct I need help with:
typedef struct _GPS_POSITION {
DWORD dwVersion;
DWORD dwSize;
DWORD dwValidFields;
DWORD dwFlags;
SYSTEMTIME stUTCTime;
double dblLatitude;
double dblLongitude;
float flSpeed;
float flHeading;
double dblMagneticVariation;
float flAltitudeWRTSeaLevel;
float flAltitudeWRTEllipsoid;
GPS_FIX_QUALITY FixQuality;
GPS_FIX_TYPE FixType;
GPS_FIX_SELECTION SelectionType;
float flPositionDilutionOfPrecision;
float flHorizontalDilutionOfPrecision;
float flVerticalDilutionOfPrecision;
DWORD dwSatelliteCount;
DWORD rgdwSatellitesUsedPRNs[GPS_MAX_SATELLITES];
DWORD dwSatellitesInView;
DWORD rgdwSatellitesInViewPRNs[GPS_MAX_SATELLITES];
DWORD rgdwSatellitesInViewElevation[GPS_MAX_SATELLITES];
DWORD rgdwSatellitesInViewAzimuth[GPS_MAX_SATELLITES];
DWORD rgdwSatellitesInViewSignalToNoiseRatio[GPS_MAX_SATELLITES];
} GPS_POSITION, *PGPS_POSITION;
Click to expand...
Click to collapse
I think the struct works like some type of callback which even that I'm not familiar with but as you try and retrieve information from the function 'GPSGetPosition' it uses the struct to do the work? just a guess...
Anyway I'm hoping someone can help me out as I feel I'm close but unless I can pull GPS data at still at ground zero...
TW,
Simple solution: Compile C# (this is NOT C+++) code to dll library. Then reference library from VB.NET solution.
C# and VB.NET are compiled both to IL.
Here is the needed code and declarations in C#.
<Your path>'Windows Mobile 6 SDK\Samples\PocketPC\CS\GPS\GpsPosition.cs"
Since I'm a bit green - are there some examples of doing this somewhere that I can take a look at?
"C# and VB.NET are compiled both to IL."
I don't follow what your saying here? what does IL stand for?
Thanks,
My friend,
why sample?
IL = Intermediate Language - VB.NET and C# are compiled to intermediatate language.
.Net Framework is languaage independent - You can compile C# code to dll and then reference (add reference) this dll in VB.NET project and use types form C# dll directly.
Thanks, I certainly appreciate your patience...
OK, I'll remember to use VB.NET as opposed to .NET in the future since there is a difference that I was unaware of, thanks for that.
Since I want to run this application on my phone I assume I need to create a new project in VB.Net - WM6 class library. Can I simply copy over the references and source form the original SDK and then build the .dll from there or am I over simplifying?
After building the .dll, in the application I want to create I make the reference to the new .dll, got it, when I want to reference the struct of the 'GPSGetPosition' function how would I do that?
TW,
[EDIT]
Doing more reading and learning a bit.
I think using a dll is the way to go and I believe there is a dll included in the sample. That brings me back to the Q of implementation. I've added a reference to the dll but since I'm only using the functions built within the dll how should I pass the GPS_POSITION struct listed above? does that still need to be converted to VB.Net then passed?
Semi manual marshhalling of structure to pointer:
Dim pointerM As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(myStruct))
Marshal.StructureToPtr(myStruct, pointerM, False)
Marshal.FreeHGlobal(pnt)
Click to expand...
Click to collapse
Since the above doesn't seem to pass anything to the struct is this used for sizing the struct to be passed?
OK.
Here is the compiled dll.
Add reference from vb.net project to dll.
Then (conceptual code in the pretty poor verbose VB.NET syntax )
Dim gps As new Gps()
AddHandler gps.DeviceStateChanged , DeviceStateChanged
AddHandler gps.LocationChanged, LocationChanged
gps.Open();
Public Sub LocationChanged(sender As object, args as LocationChangedEventArgs)
'Do something
args.Position.LatitudeInDegreesMinutesSeconds
args.position.LongitudeInDegreesMinutesSeconds
End Sub
Public Sub DeviceStateChanged(object sender, DeviceStateChangedEventArgs args)
'Do something
//GPS driver state
args.DeviceState;
End Sub
End of work with gps:
gps.Close()
//edit: Remove zip extension from gps.dll.zip - gps.dll is a valid name of assembly
RStein,
Thanks for your help. I managed to get it going with your assistance, it's much appreciated.
The .dll you compiled is not complete and errors though..
Dlli is a complete - from gps managed sample.
What's the error You're talking about?
As I said in other zda thread - intermediate driver doesn't work correctly on some Devices/ROM because of the error in the Microsoft/OEM implementaton (Htc Artemis).. http://groups.google.com/group/microsoft.public.pocketpc.developer/msg/2cedd69b906d4b7e
And finaly - GPS intermediate must be of course active in the control panel.
This is the error generated:
System.MissingMethodException was unhandled
Message: File or assembly name 'Microsoft.WindowsMobile.Samples.Location, Version=1.0.2985.26108, Culture=neutral, PublicKeyToken=null', or one of its dependencies, was not found.
System.TypeLoadException was unhandled
Message: An unhandled exception of type 'System.TypeLoadException' occurred in Unknown Module.
Click to expand...
Click to collapse
Thx,
Please rename gps.dll to Microsoft.WindowsMobile.Samples.Location.dll
And here is the project in VB - functional
I'm using VB.Net for Windows Mobile 5, but still not working
I want to use the GPS Intermediate Driver because I want to let the GPS to be used for other apps, such as the Google Maps for WM and other.
I did the following code, but I still not getting the right result... I did a program using the Serial connection, but Google Maps and other cannot use the GPS at the same time.
So... what am I doing wrong?
Here my code, any clues?
REM Declare Function GPSOpenDevice Lib "gpsapi.dll" (ByVal hNewLocationData As IntPtr, ByVal hDeviceStateChange As IntPtr, ByVal szDeviceName As String, ByVal dwFlags As Integer) As IntPtr
<DllImport("gpsapi.dll", EntryPoint:="GPSOpenDevice", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSOpenDevice(ByVal hNewLocationData As IntPtr, ByVal hDeviceStateChange As IntPtr, ByVal szDeviceName As String, ByVal dwFlags As Integer) As IntPtr
End Function
REM Declare Function GPSCloseDevice Lib "gpsapi.dll" (ByVal hGPSDevice As IntPtr) As Integer
<DllImport("gpsapi.dll", EntryPoint:="GPSCloseDevice", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSCloseDevice(ByVal hGPSDevice As IntPtr) As Integer
End Function
REM Declare Function GPSGetDeviceState Lib "gpsapi.dll" (ByVal pGPSDevice As IntPtr) As Integer
<DllImport("gpsapi.dll", EntryPoint:="GPSGetDeviceState", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSGetDeviceState(ByVal pGPSDevice As IntPtr) As Integer
End Function
REM Declare Function GPSGetPosition Lib "gpsapi.dll" (ByVal hGPSDevice As IntPtr, ByVal pGPSPosition As IntPtr, ByVal dwMaximumAge As Integer, ByVal dwFlags As Integer) As Integer
<DllImport("gpsapi.dll", EntryPoint:="GPSGetPosition", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Winapi)> _
Public Shared Function GPSGetPosition(ByVal hGPSDevice As IntPtr, ByVal pGPSPosition As GPS_POSITION, ByVal dwMaximumAge As Integer, ByVal dwFlags As Integer) As Integer
End Function
Const dwSize As Long = 0
Const dwVersion As Long = 1
Const dwFlags As Long = 0
Const dwValidFields As Long = 0
Const GPS_MAX_SATELLITES As Long = 12
<StructLayout(LayoutKind.Sequential)> Public Structure GPS_POSITION
Dim dwVersion As Long
Dim dwSize As Long
Dim dwValidFields As Long
Dim dwFlags As Long
'Dim stUTCTime As systemtime
Dim dblLatitude As Double
Dim dblLongitude As Double
Dim flSpeed As Double
Dim flHeading As Double
Dim dblMagneticVariation As Double
Dim flAltitudeWRTSeaLevel As Single
Dim flAltitudeWRTEllipsoid As Single
'GPS_FIX_QUALITY FixQuality;
'GPS_FIX_TYPE FixType;
'GPS_FIX_SELECTION SelectionType;
Dim flPositionDilutionOfPrecision As Single
Dim flHorizontalDilutionOfPrecision As Single
Dim flVerticalDilutionOfPrecision As Single
Dim dwSatelliteCount As Long
Dim rgdwSatellitesUsedPRNs() As Long
Dim dwSatellitesInView As Long
Dim rgdwSatellitesInViewPRNs() As Long
Dim rgdwSatellitesInViewElevation() As Long
Dim rgdwSatellitesInViewAzimuth() As Long
Dim rgdwSatellitesInViewSignalToNoiseRatio() As Long
End Structure
Enum GPS_FIX_QUALITY
GPS_FIX_QUALITY_UNKNOWN
GPS_FIX_QUALITY_GPS
GPS_FIX_QUALITY_DGPS
End Enum
Enum GPS_FIX_TYPE
GPS_FIX_UNKNOWN
GPS_FIX_2D
GPS_FIX_3D
End Enum
Enum GPS_FIX_SELECTION
GPS_FIX_SELECTION_UNKNOWN
GPS_FIX_SELECTION_AUTO
GPS_FIX_SELECTION_MANUAL
End Enum
<StructLayout(LayoutKind.Sequential)> Public Structure SYSTEMTIME
Public wYear As Short
Public wMonth As Short
Public wDayOfWeek As Short
Public wDay As Short
Public wHour As Short
Public wMinute As Short
Public wSecond As Short
Public wMilliseconds As Short
End Structure
Dim gpsHandle As IntPtr = IntPtr.Zero
Public Function OpenGPSDevice() As Boolean
Try
gpsHandle = GPSOpenDevice(Nothing, Nothing, Nothing, 0)
OpenGPSDevice = (gpsHandle <> 0)
MsgBox("Device is open")
Catch ex As Exception
MsgBox("Error opening GPSDevice")
End Try
End Function
Public Function CloseGPSDevice() As Boolean
Try
If gpsHandle = 0 Then Exit Function
GPSCloseDevice(gpsHandle)
gpsHandle = IntPtr.Zero
MsgBox("Device is closed")
Catch ex As Exception
MsgBox("Error closing GPSDevice")
End Try
End Function
Private Sub bmtGPS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bmtGPS.Click
Dim i As Long
Dim gpsPOS As New GPS_POSITION
Try
'gpsPOS.dwVersion = "GPS_VERSION_1"
'gpsPOS.dwSize = 512
i = GPSGetPosition(gpsHandle, gpsPOS, 500000, 0)
txtTeste.Text &= i
txtTeste.Text &= vbCrLf & "Latitude=" & gpsPOS.dblLatitude
txtTeste.Text &= vbCrLf & "Longitude=" & gpsPOS.dblLongitude
txtTeste.Text &= vbCrLf & "SatelliteCount=" & gpsPOS.dwSatelliteCount
txtTeste.Text &= vbCrLf & "SatellitesInView=" & gpsPOS.dwSatellitesInView
txtTeste.Text &= vbCrLf & "Heading=" & gpsPOS.flHeading
txtTeste.Text &= vbCrLf & "Speed=" & gpsPOS.flSpeed
txtTeste.Text &= vbCrLf & "Flags=" & gpsPOS.dwFlags
Catch ex As Exception
MsgBox("Error getting position")
End Try
End Sub
Private Sub bmtGPSOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bmtGPSOn.Click
OpenGPSDevice()
End Sub
Private Sub bmtGPSOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bmtGPSOff.Click
CloseGPSDevice()
End Sub
Thank your for the GPS Vb.Net Sample
Hi René,
Your sample help me a lot, but I still have some issues and I hope you can give me more clues.
During my tests... everything works fine, but when I tried to use some of the date from LocationChanged, it do not return data. The GPS icon is GREEN, so, it's looks like everything is fine... the Google Maps works with my apps to, but all return ""
frmPrincipal.lblLatitude.Text = e.Position.Longitude.ToString()
frmPrincipal.lblLongitude.Text = e.Position.Longitude.ToString()
frmPrincipal.lblAltitude.Text = e.Position.SeaLevelAltitude.ToString()
Other thing... why at DeviceStateChanged the only way to get data if with a INVOKE like you did?
Invoke(New UpdateDataHandler(AddressOf AddItem), e.DeviceState.FriendlyName)
And final...
As I can see... the LocationChanged, is not so acured... because it was been called every second or less... it's normal?
Best,
Ruben
RStein said:
And here is the project in VB - functional
Click to expand...
Click to collapse
Getting a error with GPS
I'm getting the following error. I get this random, as I read, the GPS API uses a file to get it's info, so... I thing could be it.
gps.GetPosition.SatellitesInViewCount.ToString Run-time exception thrown : System.IO.IOException - The process can not access the file '\Test.txt' because it is being used by another process.
With the Debug, I have the following info:
gps.GetDeviceState.FriendlyName ""
gps.GetDeviceState.DeviceState On {1}
gps.GetDeviceState.ServiceState On {1}
gps.Opened True
And the error showed it self, when I use any of the follow properties:
gps.GetPosition.LatitudeValid
gps.GetPosition.SatelliteCount
gps.GetPosition.Latitude
I saw at my PDA root folder a Test.txt and also I read that file could configured with.
http://msdn.microsoft.com/en-us/library/ms889970.aspx
Some one have any clues?
I'll continue to dig... if I post here if I get more info.
I'm using a Windows Mobile 5 the HP 6945.
With this DLL work on all device????
I made an application named "Where is" and i use the Serial Port to check the info from GPS but in some device i cant get the data and i dont know why.
With this DLL i can resolve all problems?
I work with vb.net.
Wait an answer please.
Bye

[REF/DEV] KaiserGL SDK (for Imageon on Qualcomm 72xx devices)

All REMOVED by user request.
How-to
catch going to suspend: http://forum.xda-developers.com/showthread.php?p=2776841#post2776841
* more reserved *
Following up from post getting OT in thread:
ycavan said:
My opengl es init function is called after UpdateWindow(), so I'm still stumped as to why the surface still cannot be created... here's my winmain:
Click to expand...
Click to collapse
You might be missing some of the modern WM6 calls. Here's the relevant code from the working ported version of Graphics for the Masses.
I started with working code from the AppWizard. tabs/spaces is pushing the formatting everywhere:
Code:
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
HACCEL hAccelTable;
int retval;
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_APPSTUFF));
// Main message loop:
for(;;)
{
switch(gMinimized_mode)
{
case 0:
game_loop:
while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == TRUE)
{
if (GetMessage(&msg, NULL, 0, 0) )
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
else
{
retval = (int) msg.wParam;
goto out;
}
}
if (!gMinimized_mode)
{
/* app code */
eglSwapBuffers (eglDisplay, eglWindowSurface);
if(retval == 0)
{
/* app exit code */
goto out;
}
}
break;
default:
while (GetMessage(&msg, NULL, 0, 0) )
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if (msg.message == WM_PAINT)
{
gMinimized_mode = 0;
goto game_loop;
}
}
retval = (int) msg.wParam;
goto out;
}
}
out:
return retval;
}
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPSTUFF));
wc.hCursor = 0;
wc.hbrBackground = NULL;//(HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING]; // title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name
g_hInst = hInstance; // Store instance handle in our global variable
// SHInitExtraControls should be called once during your application's initialization to initialize any
// of the device specific controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
//LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
wcscpy(szTitle, appName);
LoadString(hInstance, IDC_OGLESEXFW, szWindowClass, MAX_LOADSTRING);
//If it is already running, then focus on the window, and exit
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// set focus to foremost child window
// The "| 0x00000001" is used to bring any owned windows to the foreground and
// activate them.
SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return 0;
}
if (!MyRegisterClass(hInstance, szWindowClass))
{
return FALSE;
}
hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
// When the main window is created using CW_USEDEFAULT the height of the menubar (if one
// is created is not taken into account). So we resize the window after creating it
// if a menubar is present
if (g_hWndMenuBar)
{
RECT rc;
RECT rcMenuBar;
GetWindowRect(hWnd, &rc);
GetWindowRect(g_hWndMenuBar, &rcMenuBar);
rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
{
/* EGL Setup */
EGLContext ctx;
EGLint majorVersion;
EGLint minorVersion;
//eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglDisplay = eglGetDisplay(GetDC(hWnd));
eglInitialize(eglDisplay, &majorVersion, &minorVersion);
eglConfig = select_config(eglDisplay, EGL_WINDOW_BIT, 16, 16, 4);
ctx = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
eglWindowSurface = eglCreateWindowSurface(eglDisplay, eglConfig, hWnd, NULL);
eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, ctx);
/* rest of app init */
}
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
static SHACTIVATEINFO s_sai;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
break;
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
{
SHMENUBARINFO mbi;
memset(&mbi, 0, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = hWnd;
mbi.nToolBarId = IDR_MENU;
mbi.hInstRes = g_hInst;
if (!SHCreateMenuBar(&mbi))
{
g_hWndMenuBar = NULL;
}
else
{
g_hWndMenuBar = mbi.hwndMB;
}
// Initialize the shell activate info structure
memset(&s_sai, 0, sizeof (s_sai));
s_sai.cbSize = sizeof (s_sai);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
if (!gMinimized_mode) eglSwapBuffer();
break;
case WM_DESTROY:
eglMakeCurrent(NULL, NULL, NULL, NULL);
eglDestroyContext(eglDisplay, eglContext);
eglDestroySurface(eglDisplay, eglWindowSurface);
eglTerminate(eglDisplay);
CommandBar_Destroy(g_hWndMenuBar);
PostQuitMessage(0);
break;
case WM_SIZE:
switch(wParam)
{
case SIZE_MINIMIZED:
gMinimized_mode = 1;
break;
case SIZE_MAXIMIZED: case SIZE_RESTORED: case SIZE_MAXSHOW:
gMinimized_mode = 0;
default:
{
RECT wrect;
GetClientRect(hwnd, &wrect);
/* app resize code */
break;
}
}
break;
case WM_ACTIVATE:
// Notify shell of our activate message
SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
break;
case WM_SETTINGCHANGE:
SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
break;
case WM_KEYDOWN:
{
switch(wParam)
{
case(VK_UP):
break;
case(VK_DOWN):
break;
case(VK_LEFT):
break;
case(VK_RIGHT):
break;
case(VK_RETURN):
break;
}
if (wParam == VK_ESCAPE)
SendMessage(hwnd, WM_CLOSE, 0, 0);
break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
I'm using evc4, so I can't build for a THUMB ( wince 5.0 ) device... any way you can recompile the lib for ARMv4?
Otherwise, I'm still linking w/ the Vincent lib.
Anyway, I started a whole new app ( appwizard hello template ) instead of writing the winmain from scratch and I still cannot generate a surface when I have anything but EGL_NONE in the config requests.
One thing I note is that fps is about 47-48, but once again, the texture is not mapped onto the object. If I put it in my folder w/ the Vincent dll, the texture is mapped and the fps is about 11-12.
I'm not quite familiar w/ EGL, but... does anyone know the EGLConfig structure? I tried searching for it to see what the requested width/height per config was so I can debug why the surface just doesn't get created.
anyway, here's my code:
View attachment TestApp2.zip
ycavan said:
I'm using evc4, so I can't build for a THUMB ( wince 5.0 ) device... any way you can recompile the lib for ARMv4?
Click to expand...
Click to collapse
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
Also, Imageon may work better with GLfloat values although it probably kills Vincent (with software emulation on the ARM without native FP support in armv6 by the compiler) with anything but GLfixed. Try some benchmarking to see which works out better.
100000xtimes thanks!
can you make a sourceforce project??
NuShrike said:
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
.
Click to expand...
Click to collapse
ARMv4 is what evc4 targets...
GetClientRect() is giving me very sane values, 268x240... 268 due to the bars up top & below.
I guess I'm just confused as to why Vincent is able to properly create the proper surface while our drivers cannot...
Edit:
//eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglDisplay = eglGetDisplay(GetDC(hWnd));
eglInitialize(eglDisplay, &majorVersion, &minorVersion);
eglConfig = select_config(eglDisplay, EGL_WINDOW_BIT, 16, 16, 4);
ctx = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
eglWindowSurface = eglCreateWindowSurface(eglDisplay, eglConfig, hWnd, NULL);
eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, ctx);
/* rest of app init */
Click to expand...
Click to collapse
I just realized that you don't provide egl config attribs for for eglCreateWindowSurface or for eglCreateContext... huh. Doing that, the surface and context are created ok, but the texture still isn't loaded... mebbe a problem w/ texture loading.
NuShrike said:
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
Also, Imageon may with better with GLfloat values although it probably kills Vincent (with software emulation on the ARM without native FP support in armv6 by the compiler) with anything but GLfixed. Try some benchmarking to see which works out better.
Click to expand...
Click to collapse
In the words of the great Sammy L.
ENGLISH MOTHAF*CKA DO YOU SPEAK IT!?!
Click to expand...
Click to collapse
cp_kirkley said:
In the words of the great Sammy L.
Click to expand...
Click to collapse
That's just rude, dood... lol
Anywho, it looks like the problem w/ texturing is that our drivers do not seem to support mipmap. By commenting out the linear mipmap flag when loading the texture, we get a fully working opengl es test app. I get about 44 fps.
See for yourselves.
View attachment testapp2.zip
@nushrike, both of your libgles_cm.lib's are designed for the 'THUMB' device. It's ok. I'll just keep on linking to the vincent lib.
Just remember that our driver does not support mipmap.
I think it's eVC is too old then. It's been thumb since WinCE5. Most all the system libs I have to link to insiste on Thumb -- if I set it to ARM, it refuses to link. Hey, that's an idea.. I'll try ARM to see if it generates any .lib.
For hardware, or supported mipmapping (software or not), look up glGenerateMipmapOES(GL_TEXTURE_2D). The tech demo I posted earlier demonstrates this. It's that blurry looking rotating texture behind the checker-board and various other textures.
edit: nope, can't create a dummy .lib by trying to link ARM.
Instead, you can modify Vincent to fake-support the extended functions as you need them and as they exist in the HWA .dll exports list. Here's an example:
Code:
#ifdef __GL_EXPORTS
# define GL_API __declspec(dllexport)
#else
# define GL_API
#endif
#define GL_APICALL GL_API
#define GL_APIENTRY
#ifdef __cplusplus
extern "C" {
#endif
{
GL_APICALL void GL_APIENTRY glGenerateMipmapOES (GLenum target)
{ return; }
#ifdef __cplusplus
}
#endif
NetrunnerAT said:
can you make a sourceforce project??
Click to expand...
Click to collapse
No code to make it a SourceForge project. Now, if it was code to make the drivers, that would be worthy.
ycavan: figured out your bug. You have to pass NULL for configAttrib (the last parameter) for eglCreateContext, and eglCreateWindowSurface. Also, using glGenerateMipmapOES(GL_TEXTURE_2D) with your source, texture works fine now. Same FPS. I'm seeing if converting to GLfloat will speed it up.
edit: float is no speed increase so far, but no decrease either.
ycavan said:
105171
Click to expand...
Click to collapse
How do you get this to run? I've already asked you in PM that WinCE doesn't support the concept of "current working directory" and you use in your code.
I'm sorry about not responding to the pm's... lol, I just didn't see them.
Anyway, just unzip the file on your pc and copy the exe and resources folder to your device and run the exe. Just make sure to keep the exe and resources folder together.
ycavan said:
Anyway, just unzip the file on your pc and copy the exe and resources folder to your device and run the exe. Just make sure to keep the exe and resources folder together.
Click to expand...
Click to collapse
It doesn't work for me after I drop it into the "Program Files" folder because this code is hard-coded for root directory then.
really odd... i ran the program in its own directory w/o a problem... i'm @ work, so i'll check it out when i get home.
it looks like the "resources" directory must be on the root of the device...
I'm working on finding the cwd, but loading resources fails even though it's the correct wd...
You guys can try and see if this works...
Code:
TCHAR tPath[255];
char sPath[255];
// get full path to this executable
GetModuleFileName(NULL,tPath,255);
// find the last '\'
TCHAR* pos = wcsrchr(tPath,'\\');
// end the string after the last '\'
*(pos+1) = '\0';
// copy wide char array to multi-byte string
wcstombs(sPath,tPath,255);
sPath should contain the working directory... but my app is failing the resource loads even though this is the same full path as before...
this can be very intresting for xda flame with goforce? can you build the libs because there is no SDK avialeble, the test app doesn't work message:
OpenGL ES init error:
eglInitialize
jaikben22 said:
this can be very intresting for xda flame with goforce? can you build the libs because there is no SDK avialeble, the test app doesn't work message:
OpenGL ES init error:
eglInitialize
Click to expand...
Click to collapse
EDIT:
Just realized that you're talking about another phone w/ the goforce... lol
You will need to prolly google "goforce opengl es sdk" There should be quite a few out there.
On another note... I figured out the problem with working directory resource loading.
I prefer to make a call once when it's something configuration-related... like storing my current working directory... it seems that evc4 doesn't like it when I do that so I had to update mesh.cpp and texture.cpp to perform the GetModuleFileName calls in each load function.
Here's an updated TestApp2. You just need to keep testapp2.exe and the resources directory together.
View attachment testapp2.zip
Updates include:
+ fullscreen now
+ up/down rotation
+ left/right acceleration -100 to 100
+ spouting of particles
Have fun guys.
The resources directory contains these files that you can change if you want to try different things.
spot.raw - the particle system's balls texture
font.raw - the font texture
knot.gsd - the main object mesh
fire128.tga - the mesh object's texture
lol for goforce there are none zero nada

[WM6] Disabling taskbar, SIP and hardware keys (including green and red buttons)

Hello there!
I've seen a lot of questions on this topic, and just yesterday, my client asked for this feature implemented in the app that we are currently developing...
After a veeeery intensive and long night, i finally found how to disable all these things! The code is written in c# using .net CF 2.0, and has been tested successfully on a HTC Tynt device. The interesting thing is that it will also disable the End Call and Make Call hardware buttons (VK_TEND and VK_TTALK). If you intend to use this in a production environment you might consider improoving it a little bit.
[DllImport("coredll.dll")]
private static extern bool UnregisterFunc1(KeyModifiers modifiers, int keyID);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers Modifiers, // key-modifier options
int key //virtual-key code
);
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
Modkeyup = 0x1000,
}
private void DeactivateUI()
{
try
{
// deactivate the SIP button
IntPtr hSip = FindWindow("MS_SIPBUTTON", "MS_SIPBUTTON");
EnableWindow(hSip, false);
// deactivate the SIP button
IntPtr hTaskBar = FindWindow("HHTaskBar", null);
EnableWindow(hTaskBar, false);
// deactivate the hardware keys
for (Int32 iCounter = 193; iCounter <= 207; iCounter++)
{
UnregisterFunc1(KeyModifiers.Windows, iCounter);
RegisterHotKey(this.Handle, iCounter, KeyModifiers.Windows, iCounter);
}
UnregisterFunc1(KeyModifiers.None, 0x73); //VK_TEND
RegisterHotKey(this.Handle, 0x73, KeyModifiers.None, 0x73);
UnregisterFunc1(KeyModifiers.None, 0x72);
RegisterHotKey(this.Handle, 0x72, KeyModifiers.None, 0x72); //VK_TTALK
}
catch (Exception ex)
{
Log.WriteError(ex, false);
}
}
Cheers!
Very good, helped me a lot! But how do I unlock the keys again, without rebooting?
Thanks!
gciochina said:
Hello there!
I've seen a lot of questions on this topic, and just yesterday, my client asked for this feature implemented in the app that we are currently developing...
After a veeeery intensive and long night, i finally found how to disable all these things! The code is written in c# using .net CF 2.0, and has been tested successfully on a HTC Tynt device. The interesting thing is that it will also disable the End Call and Make Call hardware buttons (VK_TEND and VK_TTALK). If you intend to use this in a production environment you might consider improoving it a little bit.
[DllImport("coredll.dll")]
private static extern bool UnregisterFunc1(KeyModifiers modifiers, int keyID);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers Modifiers, // key-modifier options
int key //virtual-key code
);
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
Modkeyup = 0x1000,
}
private void DeactivateUI()
{
try
{
// deactivate the SIP button
IntPtr hSip = FindWindow("MS_SIPBUTTON", "MS_SIPBUTTON");
EnableWindow(hSip, false);
// deactivate the SIP button
IntPtr hTaskBar = FindWindow("HHTaskBar", null);
EnableWindow(hTaskBar, false);
// deactivate the hardware keys
for (Int32 iCounter = 193; iCounter <= 207; iCounter++)
{
UnregisterFunc1(KeyModifiers.Windows, iCounter);
RegisterHotKey(this.Handle, iCounter, KeyModifiers.Windows, iCounter);
}
UnregisterFunc1(KeyModifiers.None, 0x73); //VK_TEND
RegisterHotKey(this.Handle, 0x73, KeyModifiers.None, 0x73);
UnregisterFunc1(KeyModifiers.None, 0x72);
RegisterHotKey(this.Handle, 0x72, KeyModifiers.None, 0x72); //VK_TTALK
}
catch (Exception ex)
{
Log.WriteError(ex, false);
}
}
Cheers!
Click to expand...
Click to collapse
Can u provide the EnableWindow method.I am getting the error in this method
Implement code
Hello!
I have created app to WM 5 - 6.5, but users can close it using END button. I see your code, but i can't implement ( i mean I don't have sufficient knowledge) it to visual studio 2008.
Could you tell me what should I do?
Error 1 'APP.Kiosk' does not contain a definition for 'Handle' and no extension method 'Handle' accepting a first argument of type 'APP.Kiosk' could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\lupag\Moje dokumenty\Pobieranie\CEKiosk\CEKiosk\Kiosk.cs 155 43 CEKiosk
Handle? wtf

Categories

Resources