42Gears Speaks Driving Enterprise Mobility

29Jun/100

C# code to soft reset a Windows Mobile device

Here is the C# code to soft reset a Windows Mobile device (using P/Invoke)

[DllImport("coredll.dll", SetLastError = true)]
static extern int SetSystemPowerState(string psState, int StateFlags, int Options);

const int POWER_FORCE = 4096;
const int POWER_STATE_RESET = 0x00800000;

private void SoftReset()
{
SetSystemPowerState(null, POWER_STATE_RESET, POWER_FORCE);
}

Go to Home


19May/100

How to get information about softwares installed on Windows Mobile devices?

Best method is to ask the configuration service provider (CSP).

Step 1: Add Reference to Microsoft.WindowsMobile.Configuration
Step 2: Add the following statements at the top of the c# code file.

using System.Xml;
using Microsoft.WindowsMobile.Configuration;

Step 3: Prepare a csp string (xml format) and pass it to ProcessConfiguration method of ConfigurationManager. Return value is the xml string which contains all currently installed softwares on the device.

private void ListInstalledSoftwares()
{
string cspString = "<wap-provisioningdoc><characteristic-query type=\"UnInstall\"></characteristic-query></wap-provisioningdoc>";
XmlDocument xmlResult = null;

// Use CSP to get list of installed applications
try
{
XmlDocument configDoc = new XmlDocument();
configDoc.LoadXml(cspString);
xmlResult = ConfigurationManager.ProcessConfiguration(configDoc, false);
Debug.WriteLine(xmlResult.InnerXml);
}
catch (Exception ex)
{
Debug.WriteLine("Failed to get list of installed applications. CSP failure. [Exception: " + ex.Message + "]");
}
}

Go to Home


14May/100

How to disable “Unsigned Prompt Policy” on Windows Mobile?

Many Windows Mobile (Pocket PC) devices ship with one-tier security configuration enabled. That means if an unsigned application is started, then the user is prompted whether to allow the unsigned application to run or not. If the user based on his/her judgment allows the application to run, the application runs in privileged mode whereby it can access all system APIs and protected registry keys.

Now this feature can be very annoying during development. So rather than signing the executable the developer can temporarily disable the Unsigned Prompt Policy by making some registry changes.

Steps to disable Unsigned Prompt Policy on Windows Mobile:

  • Use Remote Registry Editor or a third-party tool such as PHM Registry Editor.
  • Set the following registry value to 1 to disable Unsigned Prompt Policy. (Default value is 0).

    ; Unsigned Prompt Policy
    [HKEY_LOCAL_MACHINE\Security\Policies\Policies]
    "0000101a"=dword:1

    Note: Create the above registry entry if it does not already exist.

Go to Home


10May/100

How to get process id and thread id from a Window Handle in .NET CF?

Specify the namespace for doing P/Invoke stuff i.e. calling Win32 API functions from managed code.

using System.Runtime.InteropServices;

GetWindowThreadProcessId Win32 function retrieves the identifiers of the process and thread that created the specified window.

Here is how we declare GetWindowThreadProcessId for use in managed code (c#).


[DllImport("coredll.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

Description:

  • hWnd is the window handle
  • lpdwProcessId stores the process identifier after the method returns
  • return value of the function is the id of the thread that created the window

Calling GetWindowThreadProcessId via P/Invoke:

// Set the hWnd value below with window handle of your interest
IntPtr hWnd = this.Handle;
uint processid = 0;
uint threadid = GetWindowThreadProcessId((IntPtr)hWnd, out processid);

And there you go....


5Apr/102

Writing “Hello World” program for Windows Phone 7

Windows Phone 7 (WP7) is a cool new mobile platform from Microsoft. Developers can use Silverlight, XNA Framework and of course .NET compact framework for developing applications for WP7.

What do you need

To get started, download and install the following tools on your Windows 7 or Vista PC.

http://www.microsoft.com/downloads/details.aspx?FamilyId=2338b5d1-79d8-46af-b828-380b0f854203&displaylang=en

Installation includes Visual Studio 2010, Expression Blend, Windows Phone Emulator, XNA Game studio along with all the documentation required for writing your next great app.

Note that if Visual Studio 2010 Professional or above is already installed on the PC then only an Add-in for Windows Phone development is installed rather than complete installation of Visual Studio 2010 Express Edition.

To familiarize with the development environment its better to first develop a simple Silverlight application.

Create Hello World Project in SilverLight

1. Launch Visual Studio and Select File -> New Project command.
2. Select SilverLight for Windows Phone as template and Windows Phone Application as project type.
3. Specify HelloWorld as project name and Click OK button.
4. Wizard will create all the necessary files as the foundation for our HelloWorld application.

What Wizard generates

Most important files are generated by the wizard are:
1. MainPage.xaml : Default page with some UI element.
2. App.xaml : This file is used to declare shared application resources like colors, brushes, fonts and various style objects. The code-behind file app.xaml.cs is used to handle global application level events like Application_Startup, Application_Exit and Application_UnhandledException.

Building the Project
Since this is the first application built with the newly installed dev environment, its good to build the default project to rule out any installation problems. Right-click on the Solution in the Solution Explorer and Select Build command.

The build is successful if you will see the following message in the output window.

"========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped =========="

All is good at this stage. Go to Windows Explorer and browse to .\HelloWorld\HelloWorld\Bin\Debug folder and you will find HelloWorld.xap which is your actual compiled and compressed Silverlight application.

Lets enhance the program by adding "Hello World" functionality :).

Adding Hello World Stuff

1. Select "My Application" text block in the design view or in XAML view and change it to say, "42Gears".
2. Select "page title" text block and change it to "Hello World".

Build the project and a new HelloWorld.xap file will be generated.

Running Hello World Program

Now you are ready to launch the application. Press F5 to start debugging or Ctrl-F5 to Start without debugging. Windows Phone 7 emulator will be launched and HelloWorld.xap will be deployed and your first application will start running on the emulator.

For the first time it will take sometime for the emulator to start. Once its running, you can hit F5 or Ctrl-F5 to quickly deploy and run your application.

Well.. thats all for the HelloWorld application for Windows Phone 7. Future posts will involve more advanced topics. Stay tuned!


22Feb/100

How to display Settings screens or Control Panel Applets in Windows Mobile?

Windows Mobile Control Panel applets are normal dlls renamed with special extension .cpl. They are actually loaded by ctlpnl.exe process.

Following code snipped is what you need if you want to show a Control Panel applet from your program. This way you make it easy for your user to change desired settings, without any “complex” navigation.

BOOL ShowControlPanelApplet(int id)
{
TCHAR szParams[32];
SHELLEXECUTEINFO execinfo = {0};
memset(&execinfo, 0, sizeof(execinfo));
execinfo.cbSize=sizeof(execinfo);
execinfo.lpFile=TEXT(“\\windows\\ctlpnl.exe”);
execinfo.lpVerb=TEXT(“open”);
// Id value determines which control applet will be launched
// For e.g. 23 for bluetooth applet
wsprintf(szParams, L”cplmain.cpl,%d”, id);
execinfo.lpParameters = szParams;
BOOL bRet=ShellExecuteEx(&execinfo);
return bRet;
}

The parameter id refers to the control panel applet that you want to show. Below is the table of id values and the corresponding applet names.

Control Panel Applet Id Values

1 Password
2 Owner Information
3 Power
4 Memory
5 About
6 Brightness
7 Screen
8 Input
9 Sounds & Notifications
10 Remove Programs
11 Menus
12 Buttons
13 Today
14
15 Beam
16 Clocks & Alarms
17 Configure Network Adapters
18 Regional Settings
19 Connections
20
21
22 Manage Certificates
23 Bluetooth
24 Error Reporting
25 GPS Settings
26
27 USB to PC

Follow us on Twitter http://twitter.com/42gears


16Dec/090

No Application.StartupPath in .NET CF! There is a solution though…

Too bad there is no straight-forward way in net CF for an application to determine its folder path from where it was launched. But following code works just fine.

string assembly = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;

string currentFolderPath = System.IO.Path.GetDirectoryName(assembly);

Enjoy...


Tagged as: No Comments
11Oct/090

Simulating key presses in your program with keybd_event function

Out of need or curiosity you might want to know how to send key presses from your native application. The core of the solution involves calling keybd_event() function which has the following prototype.

VOID keybd_event(BYTE bVk, BYTE bScan, DWORD dwFlags, DWORD dwExtraInfo);

bVk is the virtual-key code of the character. bScan is the hardware scan code. dwFlags is an important field. If KEYEVENTF_KEYUP is specified in dwFlags field, the key is being released. If not specified, the key is being pressed.

Here is a function which simulates pressing of alphanumeric characters. See winuser.h for all available virtual key codes.

void SendStringKeys(char* pszChars)
{
while (*pszChars != NULL)
{
if ( (*pszChars >= 'A') && (*pszChars <= 'Z') )
keybd_event(VK_SHIFT, 0, KEYEVENTF_SILENT, 0);

keybd_event(toupper(*pszChars), 0, KEYEVENTF_SILENT, 0);
keybd_event(toupper(*pszChars), 0, KEYEVENTF_KEYUP|KEYEVENTF_SILENT, 0);

if ( (*pszChars >= 'A') && (*pszChars <= 'Z') )
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP|KEYEVENTF_SILENT, 0);

pszChars++;
}
}

And here is an example of how to call SendStringKeys function.

int _tmain(int argc, _TCHAR* argv[])
{
SendStringKeys("Hello World.");
return 0;
}


5Oct/090

Determining IP Address of a Windows Mobile device

Code to determine IP addresses of adapters on a Windows Mobile device, using IPHelper APIs.

Add Iphlpapi.lib to linker settings.

#include "Iphlpapi.h"

PIP_ADAPTER_INFO pinfo = NULL;
ULONG OutBufLen = 0;
DWORD dwRet = GetAdaptersInfo(NULL, &OutBufLen);
if (dwRet == ERROR_BUFFER_OVERFLOW)
{
pinfo = (PIP_ADAPTER_INFO)malloc(OutBufLen);
dwRet = GetAdaptersInfo(pinfo,&OutBufLen);
while (pinfo != NULL)
{
if (dwRet==ERROR_SUCCESS)
{
PIP_ADDR_STRING pAddressList = &(pinfo->IpAddressList);
do
{
printf(pAddressList->IpAddress.String);
pAddressList = pAddressList->Next;
} while (pAddressList != NULL);
}
pinfo = pinfo->Next;
}
free(pinfo);
}


26Sep/090

Programmatically display system tray icon on Windows Mobile

As a Windows Mobile user you would have seen some icons near to the bottom right corner of the Today screen. These icons give users ability to easily launch the application or show an menu with more choices.

Tray icons on Today screen (Dell Axim)

Tray icons on Today screen (Dell Axim)

This post discusses the steps and code to put your own icon in the system tray. I will also provide a solution to a common issue with Windows Mobile whereby its not easy to know the coordinates of the icon or the coordinates where the user might have tapped within the tray area.

okay…I will take an example of a Win32 native application. The concepts will hold good even if you are programming with some other framework.
1. Declare some variables and function prototypes

// some required defines
#define WM_SYSTRAY_MSG WM_USER+1
#define ID_TRAY 1

// some variables
static NOTIFYICONDATA g_structNotifyIconData = {0};
static HWND g_hWndMain = NULL;
static HWND g_hWnd = NULL;
static WNDPROC g_fnProc = NULL;
static DWORD g_dwTapPos = 0;

LRESULT DesktopExplorerWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
2. Implement a wrapper function to show and hide tray icon.

BOOL ShowTrayIcon(HWND hWnd, BOOL bShowIcon)
{
BOOL bRet = FALSE;

g_structNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);
g_structNotifyIconData.hIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_SHOWTRAYICON));
g_structNotifyIconData.hWnd = hWnd;
g_structNotifyIconData.uCallbackMessage = WM_SYSTRAY_MSG;
g_structNotifyIconData.uFlags = NIF_MESSAGE | NIF_ICON;
g_structNotifyIconData.szTip[0] = ”;
g_structNotifyIconData.uID = ID_TRAY;

if (bShowIcon)
bRet = Shell_NotifyIcon(NIM_ADD, &g_structNotifyIconData);
else
bRet = Shell_NotifyIcon(NIM_DELETE, &g_structNotifyIconData);

return bRet;
}

Above function fills up fields in NOTIFYICONDATA structure, setting the icon resource handle, parent window handle, callback message identifier, flags specifying that uCallbackMessage and icon information is being set and an user defined ID value.
3. Call ShowTrayIcon function in WM_CREATE handler

In the WM_CREATE handler portion of the main WndProc function, call ShowTrayIcon(hWnd, TRUE).

case WM_CREATE:

ShowTrayIcon(hWnd, TRUE);


4. Add handler for WM_SYSTRAY_MSG

WM_SYSTRAY_MSG will be sent to the main window procedure (WndProc) when the user taps or clicks on the icon. We must add the following code to make some good use of the icon.

switch (message)
{
case WM_SYSTRAY_MSG:
{
switch (lParam)
{
case WM_LBUTTONDOWN:
if (ID_TRAY == wParam)
{
BOOL bRet = FALSE;
POINT pt = {0};
HMENU hTrayMenu = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_TRAY_MENU));
if (hTrayMenu)
{
HMENU hSubMenu = GetSubMenu(hTrayMenu, 0);
pt.x = LOWORD(g_dwTapPos);
pt.y = HIWORD(g_dwTapPos);
bRet = TrackPopupMenu(hSubMenu, TPM_CENTERALIGN | TPM_BOTTOMALIGN, pt.x, pt.y, 0, hWnd, NULL);
dwError = GetLastError();
DestroyMenu(hSubMenu);
DestroyMenu(hTrayMenu);
}
}
}
}
break;

Here we know that user has tapped on the icon area. As a result we can do anything that we might want. Here I an showing up a popup menu using TrackPopupMenu API. g_dwTapPos variable contains the x & y position where the user tapped on the system tray area. We will see later how we get the information in g_dwTapPos. Note that GetCursorPos() does not get us this position value on Windows Mobile whereas it works on Windows desktop.
5. Getting the tap coordinates on system tray icon

One way I found to know the coordinates where the user tapped or clicked on the taskbar is to subclass the DesktopExplorerWindow and trap WM_CANCELMODE message. In the handler for WM_CANCELMODE, calling GetMessagePos() will return the position into a g_dwTapPos variable.

//
// DesktopExplorerWindow
//
LRESULT DesktopExplorerWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
// Trap WM_CANCELMODE message
// This will get us the point at which tap occurred
case WM_CANCELMODE:
g_dwTapPos = GetMessagePos();
break;
}

return ::CallWindowProc(g_fnProc, hWnd, msg, wParam, lParam);
}

BOOL HookDesktopExplorerWindow()
{
if(g_fnProc)
return FALSE;

g_hWnd = ::FindWindow(_T(”DesktopExplorerWindow”), NULL);
if(g_hWnd)
{
g_fnProc = (WNDPROC)::SetWindowLong(g_hWnd, GWL_WNDPROC, (LONG)DesktopExplorerWindowProc);
}

return g_hWnd != NULL;
}

BOOL FreeDesktopExplorerWindow()
{
if(!g_fnProc)
return FALSE;

::SetWindowLong(g_hWnd, GWL_WNDPROC, (LONG)g_fnProc);
g_fnProc = NULL;

return TRUE;
}

HookDesktopExplorerWindow can be called from WM_CREATE handler in main Window procedure before calling ShowTrayIcon. FreeDesktopExplorerWindow can be called from WM_DESTROY handler in main Window procedure.

Tray Icon

Tray Icon


See below how the icon and popup menu shows up in my sample application.