Use at your own risk!
Code:
/*
HTC HD2 Compass interface
MilaCzeque (at) gmail.com
This program is licensed under the terms of the GNU General Public License (GPL).
*/
#include <windows.h>
#include <service.h>
struct compass_data
{
short x;
short y;
short z;
short angle;
short d;
short dummy[10]; //just to make sure nothing get overwritten
};
struct compass
{
compass_data data;
HANDLE h;
HANDLE service;
int init()
{
h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, 3, 0x80, 0 );
if( h == INVALID_HANDLE_VALUE || h == 0 )
{
h = 0;
service = RegisterService( TEXT( "SEN" ), 0, TEXT( "HTCSensorService.dll" ), 1 );
if( service == 0 )
{
return 0;
}
h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, 3, 0x80, 0 );
if( h == INVALID_HANDLE_VALUE || h == 0 )
{
h = 0;
return 0;
}
}
if( 0 == DeviceIoControl( h, 0x3000001, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( h );
h = 0;
return 0;
}
return true;
}
short update()
{
if( !h )
{
return 0;
}
DWORD read = 0;
if( 0 == DeviceIoControl( h, 0x3000003, 0, 0, &data, 0, &read, 0 ))
{
return 0;
}
else
{
return 1;
}
}
int deinit()
{
if( h )
{
if( 0 == DeviceIoControl( h, 0x3000002, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( h );
h = 0;
return 0;
}
}
return 1;
}
};
Edit:
Plese do mind that this code is licensed under GPL and so is anything based on it (including C# and VB code in this thread). This means that if you use it in your project you MUST release it under GPL (and with source code).
I'm sick of everyone ignoring this. :-(
Multitouch and the compass at a similar time?
The Leo is definately getting better!
Thanks!
Someone should inform the Layar developers about this.
maati:
Don't think that Layar would agree with GPL.
l3v5y:
It will be even better with FM Radio API working.
I had a play with this, the issue is, at current I haven't found exactly what the "angle" is. Do you know whether it's the angle between the device and North? or the bearing of the device?
It's the same number as you can see in original compass application. Angle between device and magnetic north.
MilaCzeque, thanks a lot the leo is indeed getting better and better!
I don't think you can help with this, but do you have any idea about how we might get hardware compass support in Google Maps, iGO, and other software?
I'd like to refer to this thread by the way. Thx!
Maybe someone can write program which will emulate COM port with nmea from internal gps but with heading from compass.
@MilaCzeque
Hi,
See here: http://forum.xda-developers.com/showthread.php?t=571266
Is it possible to see some sample code written in C# as well ?
Thank you very much.
Thanks!
Anyone managed to get into the proximity sensor?
Great!!!
How can this be used in C# or Vb.net ?
I dont develop in C++ for Windows Mobile.
retrieving capacitive sensor data similar. Hack touch.dll and get DeviceIOControl codes....
Can anybody translate that code in C#?
Better yet, let's make a .net library so its accessible to everyone! l3v5y?
shirreer said:
Better yet, let's make a .net library so its accessible to everyone! l3v5y?
Click to expand...
Click to collapse
That would be the best.
I tried this:
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As System.UInt32, ByVal dwShareMode As System.UInt32, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As System.UInt32, ByVal dwFlagsAndAttributes As System.UInt32, ByVal hTemplateFile As IntPtr) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function RegisterService(ByVal lpszType As String, ByVal dwIndex As System.UInt32, ByVal lpszLib As String, ByVal dwInfo As System.UInt32)
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByVal lpInBuffer As IntPtr, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As IntPtr, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Private devHandle As Integer
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then
devHandle = 0
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
Dim readBytes As System.UInt32
If devHandle = 0 Then Return False
If DeviceIoControl(devHandle, DIO_READ, 0, 0, compassData, 0, readBytes, 0) = 0 Then
Return False
Else
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
However, this does not compile:
Error 2 Value of type 'GPSLib.clsCompass.compass_data' cannot be converted to 'System.IntPtr'. C:\Dokumente und Einstellungen\Marco\Eigene Dateien\Visual Studio 2008\Projects\GPSLib\GPSLib\clsCompass.vb 44 55 GPSLib
I have no idea how to convert this instance of a struct to a int pointer... any ideas??
Solved that one. Now during run w/ this code, I get a NotSupported exception in updateData():
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As System.UInt32, ByVal dwShareMode As System.UInt32, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As System.UInt32, ByVal dwFlagsAndAttributes As System.UInt32, ByVal hTemplateFile As IntPtr) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function RegisterService(ByVal lpszType As String, ByVal dwIndex As System.UInt32, ByVal lpszLib As String, ByVal dwInfo As System.UInt32)
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByRef nInputBuffer As Integer, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As compass_data, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function DeviceIoControl(<[In]()> ByVal hDevice As Integer, <[In]()> ByVal dwIoControlCode As Integer, <[In]()> ByRef nInputBuffer As Integer, <[In]()> ByVal nInBufferSize As Integer, <Out()> ByVal lpOutBuffer As Integer, <[In]()> ByVal nOutBufferSize As Integer, <Out()> ByRef lpBytesReturned As Integer, <[In]()> ByVal lpOverlapped As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Overrides Function toString() As String
Return "X: " + compassData.x + vbNewLine _
+ "X: " + compassData.x + vbNewLine _
+ "Y: " + compassData.y + vbNewLine _
+ "Z: " + compassData.z + vbNewLine _
+ "a: " + compassData.angle + vbNewLine _
+ "d: " + compassData.d + vbNewLine
End Function
Private devHandle As Integer
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then
devHandle = 0
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle = INVALID_HANDLE_VALUE Or devHandle = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
Dim readBytes As System.UInt32
If devHandle = 0 Then Return False
If DeviceIoControl(devHandle, DIO_READ, 0, 0, compassData, 0, readBytes, 0) = 0 Then
Return False
Else
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
System.NotSupportedException was unhandled
Message="NotSupportedException"
StackTrace:
bei GPSLib.clsCompass.updateData() bei GPSLib.frmMain.Timer1_Tick(Object sender, EventArgs e) bei System.Windows.Forms.Timer._WnProc(WM wm, Int32 wParam, Int32 lParam) bei System.Windows.Forms.ApplicationThreadContext._InternalContextMessages(WM wm, Int32 wParam, Int32 lParam) bei Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain) bei System.Windows.Forms.Application.Run(Form fm) bei GPSLib.frmMain.Main()
InnerException:
Finally finished
FINALLY!
I am not sure about the meaning of the data returned however.
Code:
Imports System.Runtime.InteropServices
Public Class clsCompass
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Public Shared Function CreateFile _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Integer, _
ByVal dwShareMode As Integer, _
ByVal lpSecurityAttributes As IntPtr, _
ByVal dwCreationDisposition As Integer, _
ByVal dwFlagsAndAttributes As Integer, _
ByVal hTemplateFile As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function RegisterService _
(ByVal lpszType As String, _
ByVal dwIndex As Integer, _
ByVal lpszLib As String, _
ByVal dwInfo As Integer) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function LocalAlloc _
(ByVal uFlags As Integer, _
ByVal uBytes As Integer) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Shared Function LocalFree _
(ByVal hMem As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> _
Public Shared Function DeviceIoControl _
(<[In]()> ByVal hDevice As IntPtr, _
<[In]()> ByVal dwIoControlCode As Integer, _
<[In]()> ByVal lpInputBuffer As IntPtr, _
<[In]()> ByVal nInBufferSize As Integer, _
<Out()> ByVal lpOutBuffer As IntPtr, _
<[In]()> ByVal nOutBufferSize As Integer, _
<Out()> ByRef lpBytesReturned As Integer, _
<[In]()> ByVal lpOverlapped As IntPtr) As Integer
End Function
Const DIO_INIT As Int32 = &H3000001
Const DIO_READ As Int32 = &H3000003
Const DIO_QUIT As Int32 = &H3000002
Const INVALID_HANDLE_VALUE As Int64 = -1
Const LMEM_FIXED = &H0
Const LMEM_ZEROINIT = &H40
Const LPTR = (LMEM_FIXED Or LMEM_ZEROINIT)
Structure compass_data
Public x As Short
Public y As Short
Public z As Short
Public angle As Short
Public d As Short
Public dummy As String
End Structure
Public rdBuf(8) As Byte
Overrides Function toString() As String
Return _
"X: " + rdBuf(0).ToString + vbNewLine _
+ "Y: " + rdBuf(1).ToString + vbNewLine _
+ "Z: " + rdBuf(2).ToString + vbNewLine _
+ "a: " + rdBuf(3).ToString + vbNewLine _
+ "d: " + rdBuf(4).ToString + vbNewLine
End Function
Private devHandle As IntPtr
Private srvHandle As Integer
Public compassData As New compass_data
Public Function initCompass()
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle.ToInt32 = INVALID_HANDLE_VALUE Or devHandle.ToInt32 = 0 Then
devHandle = IntPtr.Zero
srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1)
If srvHandle = 0 Then Return False
devHandle = CreateFile("SEN0:", 0, 0, 0, 3, &H80, 0)
If devHandle.ToInt32 = INVALID_HANDLE_VALUE Or devHandle.ToInt32 = 0 Then Return False
End If
If DeviceIoControl(devHandle, DIO_INIT, 0, 0, 0, 0, 0, 0) = 0 Then Return False
Return True
End Function
Public Function updateData()
' Dim readBytes As Integer
Dim buf(8) As Byte
Dim result As Integer
Dim getMemory As New IntPtr()
If devHandle = 0 Or devHandle = IntPtr.Zero Then Return False
getMemory = LocalAlloc(LPTR, buf.Length)
Marshal.Copy(buf, 0, getMemory, buf.Length)
result = DeviceIoControl(devHandle, DIO_READ, IntPtr.Zero, 0, getMemory, buf.Length, 0, IntPtr.Zero)
Marshal.Copy(getMemory, buf, 0, buf.Length)
If getMemory <> IntPtr.Zero Then LocalFree(getMemory)
If result = 0 Then
Return False
Else
rdBuf = buf
Return True
End If
End Function
Public Function shutdownCompass()
If devHandle <> 0 Then
If DeviceIoControl(devHandle, DIO_QUIT, 0, 0, 0, 0, 0, 0) = 0 Then
Return False
Else
Return True
End If
End If
Return True
End Function
End Class
Almost there...
Mapping your buffer to short[5] gives me a fair compass heading in number 4. No idea what 1..3 are, they seem to react to the device's orientation (GSensor?)
Here's the C# code (convert it back to VB with Red-Gate's .NET Reflector if you wish):
using System;
using System.Runtime.InteropServices;
namespace Sensors
{
public interface ICompass
{
/// <summary>
/// Compass heading.
/// </summary>
double Angle { get;}
/// <summary>
/// Angle is valid
/// </summary>
bool IsValid { get;}
/// <summary>
/// Start compass sensor
/// </summary>
void Start();
/// <summary>
/// Stop compass sensor
/// </summary>
void Stop();
/// <summary>
/// Reset compass sensor
/// </summary>
void Reset();
}
public class HTCCompass:ICompass
{
private IntPtr devHandle;
private int srvHandle;
public short[] buffer = new short[5];
#region ICompass
public double Angle
{
get
{
// try to connect if necessary
if(!ready) ready = initCompass();
return ready && updateData() ? buffer[3] : -1.0;
}
}
bool ready = false;
public bool IsValid { get { return ready; } }
public void Start() { ready = initCompass(); }
public void Stop() { shutdownCompass(); ready = false; }
public void Reset() { Stop(); Start(); }
#endregion
private const int DIO_INIT = 0x3000001;
private const int DIO_QUIT = 0x3000002;
private const int DIO_READ = 0x3000003;
private const long INVALID_HANDLE_VALUE = -1L;
//private const int LMEM_FIXED = 0;
//private const int LMEM_ZEROINIT = 0x40;
//private const int LPTR = 0x40;
public bool initCompass()
{
if (this.devHandle != IntPtr.Zero)
return true;
this.devHandle = CreateFile("SEN0:", 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
if ((this.devHandle.ToInt32() == INVALID_HANDLE_VALUE) | (this.devHandle.ToInt32() == 0))
{
this.devHandle = IntPtr.Zero;
this.srvHandle = RegisterService("SEN", 0, "HTCSensorService.dll", 1);
if (this.srvHandle == 0)
return false;
this.devHandle = CreateFile("SEN0:", 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
if ((this.devHandle.ToInt32() == INVALID_HANDLE_VALUE) | (this.devHandle.ToInt32() == 0))
return false;
}
int read = 0;
if (DeviceIoControl(this.devHandle, DIO_INIT, IntPtr.Zero, 0, IntPtr.Zero, 0, out read, IntPtr.Zero) == 0)
return false;
return true;
}
public bool shutdownCompass()
{
if (this.devHandle != IntPtr.Zero)
{
int read = 0;
if (DeviceIoControl(this.devHandle, DIO_QUIT, IntPtr.Zero, 0, IntPtr.Zero, 0, out read, IntPtr.Zero) == 0)
return false;
this.devHandle = IntPtr.Zero;
}
return true;
}
public override string ToString()
{
return ("X: " + buffer[0].ToString() +
"\r\nY: " + buffer[1].ToString() +
"\r\nZ: " + buffer[2].ToString() +
"\r\nA: " + buffer[3].ToString() +
"\r\nS: " + buffer[4].ToString() +
"\r\n");
}
public bool updateData()
{
byte[] buf = new byte[10];
IntPtr getMemory = new IntPtr();
if ((this.devHandle == IntPtr.Zero) | (this.devHandle == IntPtr.Zero))
{
return false;
}
getMemory = LocalAlloc(0x40, buf.Length);
Marshal.Copy(buf, 0, getMemory, buf.Length);
int read = 0;
int result = DeviceIoControl(this.devHandle, DIO_READ, IntPtr.Zero, 0, getMemory, buf.Length, out read, IntPtr.Zero);
Marshal.Copy(getMemory, buf, 0, buf.Length);
if (getMemory != IntPtr.Zero)
{
LocalFree(getMemory);
}
if (result == 0)
{
return false;
}
Buffer.BlockCopy(buf, 0, buffer, 0, buf.Length);
return true;
}
# region PInvokes
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LocalAlloc(int uFlags, int uBytes);
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int RegisterService(string lpszType, int dwIndex, string lpszLib, int dwInfo);
[DllImport("coredll.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("coredll.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int DeviceIoControl([In] IntPtr hDevice, [In] int dwIoControlCode, [In] IntPtr lpInputBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);
#endregion
}
}
Related
I am trying to write a today plugin. I've used most of the same code from the sample but it doesn't work. The plugin displays for a few seconds then disappears.
Code:
// HelloToday2.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "todaycmn.h"
#define HELLOTODAY TEXT("HelloToday")
HINSTANCE hInst;
//HWND hWnd;
void OnPaint(HWND);
BOOL OnQueryRefreshCache(HWND, TODAYLISTITEM*);
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
hInst = (HINSTANCE)hModule;
//RegisterClass(hInst);
break;
}
case DLL_PROCESS_DETACH:
{
UnregisterClass(HELLOTODAY, hInst);
break;
}
}
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_PAINT:
OnPaint(hWnd);
break;
case WM_TODAYCUSTOM_CLEARCACHE:
break;
case WM_TODAYCUSTOM_QUERYREFRESHCACHE:
OnQueryRefreshCache(hWnd, (TODAYLISTITEM*)wParam);
break;
case WM_LBUTTONUP:
// ButtonProc();
break;
}
return 0;
}
void OnPaint(HWND hWnd)
{
PAINTSTRUCT ps;
HDC hDC;
COLORREF crText = (COLORREF)SendMessage(GetParent(hWnd), TODAYM_GETCOLOR, (WPARAM)TODAYCOLOR_TEXT, 0);
COLORREF crHighlight = (COLORREF)SendMessage(GetParent(hWnd), TODAYM_GETCOLOR, (WPARAM)TODAYCOLOR_HIGHLIGHT, 0);
TODAYDRAWWATERMARKINFO dwi;
RECT rc;
GetClientRect(hWnd, &rc);
dwi.rc = rc;
dwi.hwnd = hWnd;
dwi.hdc = hDC;
hDC = BeginPaint(hWnd, &ps);
SetTextColor(hDC, crText);
int nBkMode = SetBkMode(hDC, OPAQUE);
SetBkColor(hDC, crHighlight);
DrawText(hDC, TEXT("Hello World!"), -1, &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
SetBkMode(hDC, nBkMode);
EndPaint(hWnd, &ps);
}
BOOL OnQueryRefreshCache(HWND hWnd, TODAYLISTITEM* pItem)
{
if(!pItem)
return FALSE;
pItem->cyp = DRA::SCALEY(20);
return TRUE;
}
HWND APIENTRY InitializeCustomItem(TODAYLISTITEM *pItem, HWND hWndParent)
{
if(!pItem->fEnabled)
return NULL;
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.style = 0;
wc.lpfnWndProc = (WNDPROC)WndProc;
//wc.cbClsExtra = 0;
//wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = 0;
wc.hCursor = 0;
wc.lpszClassName = TEXT("HelloToday");
wc.hbrBackground = NULL;
RegisterClass(&wc);
HWND hWnd = CreateWindow(TEXT("HelloToday"), NULL, WS_VISIBLE | WS_CHILD, 0, 0, 240, 20, hWndParent, NULL, hInst, 0);
if(pItem->fEnabled = TRUE)
ShowWindow(hWnd, SW_SHOW);
return hWnd;
}
Dear сolleagues and development guru!
I have some stopper in Power Management. I hope somebody will help me to understand.
Technologies: C#, .NET 3.5
The main point of application:
Make beep periodically.
Main problem is:
When PocketPC in active mode application running correct, but when PocketPC went to sleep mode it does not make a beep. As I understood speaker is turned off in sleep mode (like all other devices in PocketPC).
Question:
How can I turn on speaker in sleep mode?
Simply what I need is turn on speaker, make beep and back speaker to previous mode without wake up all device.
I tried code like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
for (; ; )
{
// set D0 power value
IntPtr handle = SetPowerRequirement(deviceName, DevicePowerState.D0, 1, IntPtr.Zero, 0);
// make a beep
SystemSounds.Beep.Play();
// set default power value
ReleasePowerRequirement(handle);
Thread.Sleep(10000);
}
}
}
}
And like this:
Code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Media;
using System.Threading;
using System.Runtime.InteropServices;
namespace TestProject
{
static class Program
{
public const int POWER_NAME = 0x00000001;
public enum DevicePowerState : int
{
Unspecified = -1,
D0 = 0,
D1,
D2,
D3,
D4,
}
[DllImport("coredll.dll", SetLastError = true)]
public static extern int SetDevicePower(
string pvDevice,
int dwDeviceFlags,
DevicePowerState DeviceState
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr SetPowerRequirement(
string device,
DevicePowerState state,
uint deviceFlags,
IntPtr systemState,
ulong stateFlags
);
[DllImport("coredll.dll", SetLastError = true)]
public static extern int ReleasePowerRequirement(IntPtr handle);
[MTAThread]
static void Main()
{
MessageBox.Show("Application is running...", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
string deviceName = "WAV1:"; // speaker
int resDevicePowerOn = SetDevicePower(deviceName, POWER_NAME, DevicePowerState.D0);
for (; ; )
{
// make a beep
SystemSounds.Beep.Play();
Thread.Sleep(10000);
}
}
}
}
But any of these codes does not work - there are no beep in sleep mode.
Hi, I just happened to find an article from codeproject.
You may want to take a look at it.
http://www.codeproject.com/KB/mobile/WiMoPower1.aspx
I think what you need is cerunappattime.
It seems you are enabling the audio device to run in low-power mode, but you are not actually telling the CPU to keep running ("unattended mode").
Lookup PowerPolicyNotify, specifically PPN_UNATTENDEDMODE.
You may also need to periodically call SHIdleTimerResetEx and/or SystemIdleTimerReset to keep the device active in unattended mode or it will still truely suspend.
Prevent the system enter sleep mode
The system will stop all activitis when the system enter sleep mode.So you must prevent the system enter sleep mode.
The system sleep mode:
on -> unattended -> suspend
You can run:
on -> unattended -> resuming
my code:time up is system on
ex file:screenblack.rar
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace ScreenBlack
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//取得系統狀態 Get system state
[DllImport("Coredll.dll", SetLastError = true)]
public static extern int GetSystemPowerState(StringBuilder PowerState, int length, ref int Flags);
//設定系統電源狀態
[DllImport("Coredll.dll")]
public static extern int SetSystemPowerState(int psState, int StateFlags, int Options);
public const int POWER_STATE_ON = 0x12010000;
public const int NULL = 0;
public const int POWER_FORCE = 0x00001000;
private void Form1_Load(object sender, EventArgs e)
{
//設定 timer1 的設定值 0.5 秒 Set timer1 activie in 0.5 second
timer1.Interval = 500;
//啟動定時器 Start timer1
timer1.Enabled = true;
}
//宣告變數判斷是否有改變 suspend 0:沒有改變 1:有改變
int change = 0;
//宣告變數判斷執行秒數 10
int second = 20;
private void timer1_Tick(object sender, EventArgs e)
{
//設定其標為 0
int flags = 0;
//取得系統狀態名稱 on、suspend、unattended、resuming
StringBuilder stb = new StringBuilder(260);
//取得系統狀態 Get Current system state
GetSystemPowerState(stb, stb.Capacity, ref flags);
//判斷目前系統狀態
if (flags.ToString() == "4194304")
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "268435456", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 1;
}
else if (flags.ToString() == "268435456")
{
//秒數減一
second--;
//判斷 second 是否等於零
if (second == 0)
{
//************
// your code
//************
//system on
SetSystemPowerState(NULL, POWER_STATE_ON, POWER_FORCE);
//設定秒數
second = 20;
}
}
else
{
//判斷是否有改變
if (change == 1)
{
//改變 unattended 為 resuming Chang unattended into resuming
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State\Suspend", true);
reg.SetValue("Flags", "2097152", RegistryValueKind.DWord);
reg.Close();
//設定 reg 有改變
change = 0;
//設定秒數
second = 20;
}
}
}
}
}
I'm looking for a way to turn off the data (GRPS)
Search didn't brought me anything usefull, I'm sure there is somwhere the data but can't find it.
I'm especially need it for WM 6.5 (HD2)
Search around for Modaco's NoData program. It's late and I'm too tired to search it up for you right now.
kekkle said:
Search around for Modaco's NoData program. It's late and I'm too tired to search it up for you right now.
Click to expand...
Click to collapse
Thanks for the replay but it’s not what I meant, sorry for not be clarify.
I know the NoData app and actually i just finish writing something similar but more user friendly, hope to release it asap (Now I have problem with the icon )
What I’m looking is a way to turn off programmatically the data connection of the device, what the CommManager in the HTC sense do.
I tried to use the RAS api but it didn't work
look for jmlcomm.exe here at xda and use it in your app.simple command line call.and free to use.
MichelDiamond said:
look for jmlcomm.exe here at xda and use it in your app.simple command line call.and free to use.
Click to expand...
Click to collapse
Thanks for the idea, I'll try it.
But I prefer to do it directly from my app. without calling external tool.
I found a solution!
Its from few posts in the net, don't remember where exactly with some modification of me.
here is the code I use, if someone else will need it:
Code:
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace RasHelper
{
class RasHelper
{
private const int SUCCESS = 0;
private const int ERROR_NOT_ENOUGH_MEMORY = 8;
private const int RASBASE = 600;
private const int ERROR_BUFFER_TOO_SMALL = RASBASE + 3;
private const int ERROR_INVALID_SIZE = RASBASE + 32;
// --- RASCONN data structure definition (refer to ras.h) --
private const int RAS_MaxEntryName = 20;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RASCONN
{
public int dwSize;
public IntPtr hrasconn;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxEntryName + 1)]
public string szEntryName;
}
// --------------------------------------------
[DllImport("coredll.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern uint RasEnumConnections(
[In, Out] RASCONN[] rasconn,
[In, Out] ref int cb,
[Out] out int connections);
[DllImport("coredll.dll")]
private static extern uint RasHangUp(IntPtr pRasConn);
/// <summary>
/// Returns all active RAS connections as an array of data structure RASCONN
/// </summary>
/// <returns></returns>
public static RASCONN[] GetAllConnections()
{
RASCONN[] tempConn = new RASCONN[1];
RASCONN[] allConnections = tempConn;
tempConn[0].dwSize = Marshal.SizeOf(typeof(RASCONN));
int lpcb = tempConn[0].dwSize;
int lpcConnections = 0;
uint ret = RasEnumConnections(tempConn, ref lpcb, out lpcConnections);
if (ret == ERROR_INVALID_SIZE)
{
throw new Exception("RAS: RASCONN data structure has invalid format");
}
else if (ret == ERROR_BUFFER_TOO_SMALL && lpcb != 0)
{
// first call returned that there are more than one connections
// and more memory is required
allConnections = new RASCONN[lpcb / Marshal.SizeOf(typeof(RASCONN))];
allConnections[0] = tempConn[0];
ret = RasEnumConnections(allConnections, ref lpcb, out lpcConnections);
}
// Check errors
if (ret != SUCCESS)
{
throw new Exception("RAS returns error: " + ret);
}
if (lpcConnections > allConnections.Length)
{
throw new Exception("RAS: error retrieving correct connection count");
}
else if (lpcConnections == 0)
{
// if there are no connections resize the data structure
allConnections = new RASCONN[0];
}
return allConnections;
}
/// <summary>
/// Closes all active RAS connections
/// </summary>
/// <returns></returns>
public static void CloseAllConnections()
{
RASCONN[] connections = GetAllConnections();
for (int i = 0; i < connections.Length; ++i)
{
//MessageBox.Show(connections[i].ToString());
RasHangUp(connections[i].hrasconn);
}
}
/// <summary>
/// Check if there are open data connections
/// </summary>
/// <returns></returns>
public static bool IsConnectionsOpen()
{
RASCONN[] connections = GetAllConnections();
if (connections.Length > 0)
return true;
else
return false;
}
}
}
Hello experts,
I am using : vs 2008 – MFC – Smart Device – dlg (Windows Mobile)
I tried to write c++ codes to have access to hardware compass parameters on the bases of sample codes I saw in this forum , but I had no success. My codes are :
.h file
public:
struct compass_data
{
short x;
short y;
short z;
short angle;
short d;
short dummy[10]; //just to make sure nothing get overwritten
};
struct compass
{
compass_data* data;
HANDLE h;
HANDLE service;
int init();
short update();
int deinit();
};
.cpp file
struct Crotate1Dlg::compass cmps;
cmps.init();
for(int iii=0; iii<5; iii++)
{
cmps.update();
char buffer1[65];_itoa_s(myangle, buffer1, 65, 10);//myangle is integer and initializes 9999
SetDlgItemText(IDC_mySTATIC1, (CString)buffer1);
}
cmps.deinit();
}
int Crotate1Dlg::compass::init()
{
Crotate1Dlg::compass::h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, OPEN_EXISTING, 0x80, 0 );
if( Crotate1Dlg::compass::h == INVALID_HANDLE_VALUE || Crotate1Dlg::compass::h == 0 )
{
Crotate1Dlg::compass::h = 0;
Crotate1Dlg::compass::service = RegisterService( TEXT( "SEN" ), 0, TEXT( "HTCSensorService.dll" ), 1 );
if( Crotate1Dlg::compass::service == 0 )
{
return 0;
}
Crotate1Dlg::compass::h = CreateFile( TEXT( "SEN0:" ), 0, 0, 0, OPEN_EXISTING, 0x80, 0 );
if( Crotate1Dlg::compass::h == INVALID_HANDLE_VALUE || Crotate1Dlg::compass::h == 0 )
{
Crotate1Dlg::compass::h = 0;
return 0;
}
}
if( 0 == DeviceIoControl( Crotate1Dlg::compass::h, DIO_INIT, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( Crotate1Dlg::compass::h );
Crotate1Dlg::compass::h = 0;
return 0;
}
return true;
}
short Crotate1Dlg::compass::update()
{
if( !Crotate1Dlg::compass::h )
{
return 0;
}
DWORD read = 0;
if( 0 == DeviceIoControl( Crotate1Dlg::compass::h, DIO_READ, 0, 0, Crotate1Dlg::compass::data, 5, &read, 0 ))
{
myangle = (int)Crotate1Dlg::compass::data->angle;
return 0;
}
else
{
return 1;
}
}
int Crotate1Dlg::compass::deinit()
{
if( Crotate1Dlg::compass::h )
{
if( 0 == DeviceIoControl( Crotate1Dlg::compass::h, 0x3000002, 0, 0, 0, 0, 0, 0 ))
{
CloseHandle( Crotate1Dlg::compass::h );
Crotate1Dlg::compass::h = 0;
return 0;
}
}
return 1;
}
This code compiles fine, deploys on emulator with no error (does not give proper output of course) , but gives error on the device (HTC HT2) . I am sure I am doing something wrong , please correct me.
Thank you in advance.
any screenshots ?
HTC compass
All I get on screen is : "A problem has occured with Test1.exe" then asks me to report to Microsoft .
I found a code by c#:
Code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
namespace ExtendedCF {
public static class WinApi
{
#region Icons
[DllImport("coredll.dll")]
public static extern bool DestroyIcon(IntPtr hIcon);
#endregion
#region SHGetFileInfo
[DllImport("coredll.dll", CharSet = CharSet.Auto)]
public static extern int SHGetFileInfo(
string pszPath,
int dwFileAttributes,
out SHFILEINFO psfi,
uint cbfileInfo,
SHGFI uFlags);
[Flags]
public enum SHGFI : int
{
/// <summary>get icon</summary>
Icon = 0x000000100,
/// <summary>get display name</summary>
DisplayName = 0x000000200,
/// <summary>get type name</summary>
TypeName = 0x000000400,
/// <summary>get attributes</summary>
Attributes = 0x000000800,
/// <summary>get icon location</summary>
IconLocation = 0x000001000,
/// <summary>return exe type</summary>
ExeType = 0x000002000,
/// <summary>get system icon index</summary>
SysIconIndex = 0x000004000,
/// <summary>put a link overlay on icon</summary>
LinkOverlay = 0x000008000,
/// <summary>show icon in selected state</summary>
Selected = 0x000010000,
/// <summary>get only specified attributes</summary>
Attr_Specified = 0x000020000,
/// <summary>get large icon</summary>
LargeIcon = 0x000000000,
/// <summary>get small icon</summary>
SmallIcon = 0x000000001,
/// <summary>get open icon</summary>
OpenIcon = 0x000000002,
/// <summary>get shell size icon</summary>
ShellIconSize = 0x000000004,
/// <summary>pszPath is a pidl</summary>
PIDL = 0x000000008,
/// <summary>use passed dwFileAttribute</summary>
UseFileAttributes = 0x000000010,
/// <summary>apply the appropriate overlays</summary>
AddOverlays = 0x000000020,
/// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
OverlayIndex = 0x000000040,
}
/// <summary>Maximal Length of unmanaged Windows-Path-strings</summary>
private const int MAX_PATH = 260;
/// <summary>Maximal Length of unmanaged Typename</summary>
private const int MAX_TYPE = 80;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEINFO
{
public SHFILEINFO(bool dummy)
{
hIcon = IntPtr.Zero;
iIcon = 0;
dwAttributes = 0;
szDisplayName = "";
szTypeName = "";
}
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)]
public string szTypeName;
};
#endregion
}
public static class Utils
{
#region GetFileIcon and GetFolderIcon
/// <summary>
/// Get the associated Icon for a file or application. Always returns
/// an icon. If the filePath is invalid, the default icon for files of such type is returned.
/// </summary>
/// <param name="filePath">full path to the file</param>
/// <param name="bSmall">if true, return the 16x16 icon; otherwise, the 32x32 icon</param>
/// <returns></returns>
private static Icon GetIcon(string filePath, bool bFolder, bool bSmall)
{
WinApi.SHFILEINFO info = new WinApi.SHFILEINFO(true);
int cbFileInfo = Marshal.SizeOf(info);
WinApi.SHGFI flags = WinApi.SHGFI.Icon | WinApi.SHGFI.UseFileAttributes;
if (bSmall)
flags |= WinApi.SHGFI.SmallIcon;
else
flags |= WinApi.SHGFI.LargeIcon;
int fileAttributes = 0;
if (bFolder)
{
fileAttributes = (int)FileAttributes.Directory;
}
WinApi.SHGetFileInfo(filePath, fileAttributes, out info, (uint)cbFileInfo, flags);
Icon rv = (Icon)Icon.FromHandle(info.hIcon).Clone();
WinApi.DestroyIcon(info.hIcon);
return rv;
}
private static Icon GetIcon(string filePath, bool bFolder)
{
return GetIcon(filePath, bFolder, false);
}
public static Icon GetFileIcon(string filePath)
{
return GetIcon(filePath, false);
}
public static Icon GetFolderIcon(string folderPath)
{
return GetIcon(folderPath, true);
}
public static Icon GetFileIcon(string filePath, bool bSmall)
{
return GetIcon(filePath, false, bSmall);
}
public static Icon GetFolderIcon(string folderPath, bool bSmall)
{
return GetIcon(folderPath, true, bSmall);
}
#endregion
}
}
I use convert,C# to VB.Net
When I test my program, it throw an exception.
Is there an other way to get icon?