.NET Xpress

Microsoft Technology Xplicit

Archive for the ‘Win Mobile’ Category

SQLCE Demo

Posted by anandkumar2004 on May 7, 2009

There are several ways to setup SQLCE database in mobile device. I usually prefer SQL replication in this demo I am trying to create database and tables programmatically so when you launch the application it will create the database if it is not present in the device.

In order to make it more clear I have created a class called  SqlCeHelper. Primary objective of this class is
Create Database if not available
Establish connection on request
Insert data into table
Perform queries
Close database on request

I have also created two windows forms to add and view data. This is a very simple application, hope this will help to those who are trying to know how to work with SQLCE database

Click Here to down the source code

Cheers
Anand

Posted in Win Mobile | Leave a Comment »

Prevent Idle State

Posted by anandkumar2004 on May 6, 2009

Recently a mobile developer posted me a query how to prevent system idle time?  Indeed in some scenario you must consider this lets say stops the device from sleeping when its playing a video without manually adjust the power setting because most of the end users do not understand properly the power saver concept in win CE   . The point to be notice is  idle time is  60 seconds that means we need to awake the processer before elapse of 60 seconds .Here is the sample code  to Implement this I am using the PowerManagement class of OpenNETCF library

using System;
using OpenNETCF.WindowsCE;

public class SampleClass
{
//Timer thread
private static System.Threading.Timer preventIdleThread;

public SampleClass()
{
//call the delegate elapse of 59 seconds
preventIdleThread = new System.Threading.Timer(new TimerCallback(Reactivate),
null, 0, 59 * 1000);
}

private static void Reactivate()
{
//Powermanagement class of OpenNetCF
PowerManagement.ResetSystemIdleTimer();

}
}

HTH

Cheers
Anand

Posted in Win Mobile | Leave a Comment »

Kill if Running

Posted by anandkumar2004 on March 31, 2009

Recently I got a query from a reader to know how to kill an application if it is running  in Windows Mobile 5.0, this is a very interesting question .To do this you need to capture the snapshot of current processes by calling  CreateToolhelp32Snapshot  API and then get each process name from the process list finally  kill the process if its matches with the application name passed as parameter

 

using System;

using System.Runtime.InteropServices;

using System.Collections.Generic;

 

 

public class Class1

{

    [DllImport("toolhelp.dll")]

    public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid);

    [DllImport("coredll.dll")]

    private static extern IntPtr OpenProcess(int flags, bool fInherit, int PID);

    private const int PROCESS_TERMINATE = 1;

    [DllImport("coredll.dll")]

    private static extern bool TerminateProcess(IntPtr hProcess, uint ExitCode);

    [DllImport("CoreDll.dll")]

    private extern static Int32 CloseHandle(IntPtr hProcess);

    private const int TH32CS_SNAPPROCESS = 0×00000002;

    private const int PROCESS_TERMINATE = 1;

    private const int INVALID_HANDLE_VALUE = -1;

    public Class1()

    {

    }

    public void ShutDownApp(string appName)

    {

 

        //get the sanpshot of the processlist

        IntPtr handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

        if ((int)handle > 0)

        {

 

            byte[] data, tempBuffer;

            data = new byte[564];

            tempBuffer = BitConverter.GetBytes(564);

            Buffer.BlockCopy(tempBuffer, 0, data, 0, tempBuffer.Length);

            //initialize a empty buffer

            byte[] buffer = data;

            //get the snapshot of the process

            int sanpshotStatus = Process32First(handle, buffer);

            while (sanpshotStatus == 1)

            {

                //Retrive ProcessID,ProcessName

                uint ProcessID = BitConverter.ToUInt32(buffer, 8);

                //extract the process name

                string ProcessName = Encoding.Unicode.GetString(buffer, 36, 256);

                ProcessName = ProcessName.Substring(0, ProcessName.IndexOf());

                if (ProcessName == appName) //if application is running then kill the app

                {

                    IntPtr termProcess;

                    termProcess = OpenProcess(PROCESS_TERMINATE, false, (int)ProcessID);

                    if (termProcess != (IntPtr)INVALID_HANDLE_VALUE)

                    {

                        TerminateProcess(termProcess, 0);

                        CloseHandle(termProcess);

                        break;

                    }

                }

                sanpshotStatus = Process32Next(handle, buffer);

            }

            //Close handle

            CloseToolhelp32Snapshot(handle);

        }

    }

}

 

Cheers

Anand

Posted in Win Mobile | Leave a Comment »

Activate VPN

Posted by anandkumar2004 on March 12, 2009

Most of the corporate mobile devices ship with VPN to connect to  corporate network  to access Email or shared folder  or even your application may need to call intranet web service .In this example I am demonstrating how to activate VPN programmatically user  ConnectionManager  class of openNetCF.Net library

 

using System;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Net;

namespace Demo
{
    public class SampleNetworkManager
    {
        private ConnectionManager conManager;
        public SampleNetworkManager()
        {
            conManager = new OpenNETCF.Net.ConnectionManager();
        }

        public void ConnectNetwork()
        {

            foreach (DestinationInfo destInfo in conManager.EnumDestinations())
            {
               //VPN name
                if (destInfo.Description == “My Work Network”)
                {

                    //wait till connection establish
                    conManager.Connect(destInfo.Guid, true, ConnectionMode.Synchronous);

                    if (conManager.Status == 1)
                    {
                        MessageBox.Show(“Connected”);
                        break;
                    }
                }
            }
        }
        public void DisconnectNetwork()
        {
            
                 conManager.RequestDisconnect();

            
        }

    }

}

Cheers

Anand

 

Posted in Win Mobile | Leave a Comment »

What is your Phone Number ?

Posted by anandkumar2004 on March 11, 2009

In windows mobile development environment some time you may want to know the mobile number of the device , here is the sample code to get the mobile number of the device .HTH

 using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;

public class Class1
{
    public Class1()
    {
    }
    private extern IntPtr SmsGetPhoneNumber(IntPtr psmsaAddress);
    private string GetPhoneNumber()
    {
        Byte[] buffer = new Byte[516];
        string phoneNumber = “”;
        fixed (byte* pAddr = buffer)
        {

            IntPtr res = SmsGetPhoneNumber((IntPtr)pAddr);
            byte* pCurrent = pAddr;
            PhoneAddressType = (AddressType)Marshal.ReadInt32((IntPtr)pCurrent);
            pCurrent += Marshal.SizeOf(PhoneAddressType);
            honeNumber = Marshal.PtrToStringUni((IntPtr)pCurrent);

            return honeNumber;
        }
    }
    public string PhoneNumber
    { get { return GetPhoneNumber(); } }
}

This code will work only to those devices which support SIM card

 

Cheers

Anand

Posted in Win Mobile | Leave a Comment »

What is the Backlight Name?

Posted by anandkumar2004 on June 25, 2008

Recently couple of readers  like to know how to get the backlight name programmatically i.e  the backlight name will differ from device to device .Here is the sample code  to get the backlight name of your device

public string GetBackLightName()

    {

        string bklName = “”;

            OnFlag = false;

            RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@”\System\CurrentControlSet\Control\Power\State\BacklightOff”);

            if (regKey != null)

            {

                string[] keyName = regKey.GetValueNames();

                foreach (string keyVal in keyName)

                {

                    if (keyVal.IndexOf(“:”) > 0)

                    {

                        bklName = keyVal;

                        break;

                    }

                }

                regKey.Close();

            }

            return bklName;

    }

 

The backlight name and few configuration settings available in HKLM\System\CurrentControlSet\control\Power.

Posted in Win Mobile | Leave a Comment »

Lights ON…..

Posted by anandkumar2004 on June 21, 2008

 

Today I am going  to talk about how to turn  ON/OFF and Reset the back light of a mobile device  , core.dll provide a function called SetDevicePower(..) which helps to ON the back light one point to keep in mind that if you do not reset it will be ON until you reboot the device so its important to reset once you done with your task .Here is the sample code to ON/OFF or reset the back light.

 

 

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;

 

namespace LightON

{

    public partial class Form1 : Form

    {

        [DllImport("coredll.dll", SetLastError = true)]

        public static extern int SetDevicePower(string pvDevice,

             int dwDeviceFlags, int state);

        public const int POWER_NAME = 0×00000001;

        private static String BackLightName = “bkl1″;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btnOn_Click(object sender, EventArgs e)

        {

            SetDevicePower(BackLightName, POWER_NAME, 0);

        }

 

        private void btnReset_Click(object sender, EventArgs e)

        {

            SetDevicePower(BackLightName, POWER_NAME, -1);

        }

 

        private void btnoff_Click(object sender, EventArgs e)

        {

            SetDevicePower(BackLightName, POWER_NAME, 4);

        }

    }

}

 

 

 

Posted in Win Mobile | 1 Comment »

Whom am I trageting to ?

Posted by anandkumar2004 on June 18, 2008

In  your regular development work  you may need to know on which device your application is running ,  this is nothing but the OEM info you can query SystemParametersInfo  to get the answer .Today I am talking about how to get the OEMInfo of the mobile device , SystemParametersInfo  API helps to retrive or set varous  windows mobile deivce settings for more informaion visit http://msdn.microsoft.com/en-us/library/aa932539.aspx . In this sample code I am trying to demonstrate how to retrive the OEM information

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;

 

 

namespace SingleInstance

{

    public partial class Form1 : Form

    {

 

        [DllImport("coredll.dll")]

        extern private static int SystemParametersInfo(uint uiAction, uint uiParam, StringBuilder pvParam, uint fWinIni);

        private static uint SPI_GETOEMINFO = 258;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

           

            StringBuilder OemInfo = new StringBuilder(50);

            SystemParametersInfo(SPI_GETOEMINFO, 50, OemInfo, 0);

            MessageBox.Show(OemInfo.ToString());

 

        }

    }

}

Posted in Win Mobile | Leave a Comment »

one and only one

Posted by anandkumar2004 on June 17, 2008

This is one of the interesting challenge for the  windows mobile developer to make sure only a single instance of the applicaiton should be in running  .After investigating various options I personally like this approach

 

using System;

using System.Collections.Generic;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

namespace SingleInstance

{

    public  class Program

    {

        [DllImport("Coredll.dll", SetLastError = true)]

        static extern IntPtr CreateEvent(IntPtr alwaysZero, bool manualReset, bool initialState, string name);

        [DllImport("Coredll.dll", SetLastError = true)]

        static extern int CloseHandle(IntPtr handle);

        private IntPtr _eventHandle = IntPtr.Zero;

        private bool oneInstance;

 

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [MTAThread]

        static void Main()

        {

            Program prg = new Program();

            prg.CreateInstance(“SingleInstance”);

            if (prg.IsCreated)

                 Application.Run(new Form1());

        }

        public void Release()

        {

            if (_eventHandle != IntPtr.Zero)

                CloseHandle(_eventHandle);

        }

        public void CreateInstance(string appName)

        {

            _eventHandle = CreateEvent(IntPtr.Zero, true, false, appName + “Event”);

            if (Marshal.GetLastWin32Error() == 0)

            {

                oneInstance = true;

            }

            else

            {

                oneInstance = false;

            }

        }

        private bool IsCreated

        {

            get { return oneInstance; }

        }

    }

}

 

 

 

Posted in Win Mobile | Leave a Comment »

ShutDown and Reboot

Posted by anandkumar2004 on June 16, 2008

Some development scnario  you may need to shutdown or reboot the deivce programatically , here is the code snippet how to do it . AYGShell library provide various method to interact with core OS , ExitWindowsEx is one of them which helps to shutdown or restart the device

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;

 

namespace RebootApp

{

    public partial class Form1 : Form

    {

        [DllImport("aygshell.dll", SetLastError=true)]

        static extern bool ExitWindowsEx(int uFlags, int dwReserved);

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btnReboot_Click(object sender, EventArgs e)

        {

            ExitWindowsEx( (int) FlagVal.REBOOT, 0);

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            ExitWindowsEx((int)FlagVal.SHUTDOWN, 0);

        }

        public enum FlagVal

        {

            LOGOFF = 0,

            SHUTDOWN = 1,

            REBOOT = 2,

            FORCE = 4,

            POWEROFF = 8

        }

 

 

    }

}

 

Posted in Win Mobile | Leave a Comment »