通過WIFI或者GPRS獲得時間,解決Windows Mobile換電池掉時間的問題

來源:互聯網
上載者:User

轉自:http://blog.csdn.net/ppCuda/archive/2010/01/03/5123011.aspx

時隔1年多了,我的WM5換電池都會掉時間。雖然網上出現了一些校準工具,但是對我的Atom Exec好像都不管用。

於是就在上一個版本的基礎上增加了自動WIFI串連互連網時間校準和自動GPRS時間校準。C#版的

首先是開啟和關閉WIFI功能

        /// <summary>
        /// 設定WifI的狀態,開啟/關閉
        /// </summary>
        /// <param name="open">true為開啟WIFI,false為關閉WIFI</param>
        /// <returns>操作成功返回true</returns>
        private bool setwifistate(bool open)
        {
            //尋找註冊表獲得WIFI裝置名稱,再將WIFI電源開啟
            bool ret = false;
            string[] sNames = null;
            RegistryKey keyWlan = null;
            try
            {
                keyWlan = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Power\State");
                sNames = keyWlan.GetValueNames();
            }
            catch { }
            finally
            {
                if (keyWlan != null) keyWlan.Close();
            }

            foreach (string wl in sNames)
            {
                if (wl.StartsWith("{98C5250D-C29A-4985-AE5F-AFE5367E5006}\\"))
                {
                    //POWER_NAME = 0x00000001
                    SetDevicePower(wl, 0x00000001, open ? DevicePowerState.D0 : DevicePowerState.D4);
                    ret = true;
                    break;
                }
            }
            return ret;
        }

然後是檢查WIFI是否已經串連上一個熱點了,這個需要不斷的check

       /// <summary>
        /// 查看WifI串連熱點狀態
        /// </summary>
        /// <returns>true為串連上一個熱點</returns>
        private bool checkwificonstate()
        {
            bool ret = false;
            RegistryKey keyWlan = null;
            try
            {
                keyWlan = Registry.LocalMachine.OpenSubKey(@"System\State\Hardware");
                int value = (int)keyWlan.GetValue("wifi", 0);
                if (value >= 0x00000010)
                {
                    ret = true;
                }
            }
            catch { }
            finally
            {
                if (keyWlan != null) keyWlan.Close();
            }
        
            return ret;
        }

以上是wifi串連開啟熱點,接下來是開啟GPRS查詢

GPRS的開啟主要是依靠ConnMgrEstablishConnectionSync這個函數來實現,網上查詢到一個ConnectionManager的類封裝了這一操作,我就拿出來跟大家一起分享!

  public class ConnectManager
    {
        const int S_OK = 0;
        const uint CONNMGR_PARAM_GUIDDESTNET = 0x1;
        const uint CONNMGR_PRIORITY_USERINTERACTIVE = 0x08000;
        const uint INFINITE = 0xffffffff;
        const uint CONNMGR_STATUS_CONNECTED = 0x10;
        const int CONNMGR_MAX_DESC = 128;    // @constdefine Max size of a network description

        const int CONNMGR_FLAG_PROXY_HTTP = 0x1; // @constdefine HTTP Proxy supported
        const int CONNMGR_FLAG_PROXY_WAP = 0x2; // @constdefine WAP Proxy (gateway) supported
        const int CONNMGR_FLAG_PROXY_SOCKS4 = 0x4; // @constdefine SOCKS4 Proxy supported
        const int CONNMGR_FLAG_PROXY_SOCKS5 = 0x8; // @constdefine SOCKS5 Proxy supported

        const UInt16 IDC_WAIT = 32514;
        const UInt16 IDC_ARROW = 32512;

        private IntPtr m_hConnection = IntPtr.Zero;

        public ConnectManager()
        {
        }

        ~ConnectManager()
        {
            ReleaseConnection();
        }

        /// <summary>
        /// 查看串連是否可用
        /// </summary>
        /// <returns></returns>
        public bool GetConnMgrAvailable()
        {
            IntPtr hConnMgr = ConnMgrApiReadyEvent();
            bool bAvailbale = false;
            uint dwResult = WaitForSingleObject(hConnMgr, 2000);

            if (dwResult == 0)
            {
                bAvailbale = true;
            }

            // 關閉
            if (hConnMgr.ToInt32() != 0) CloseHandle(hConnMgr);

            return bAvailbale;
        }
        /// <summary>
        /// 映射URL
        /// </summary>
        /// <param name="lpszURL"></param>
        /// <param name="guidNetworkObject"></param>
        /// <param name="pcsDesc"></param>
        /// <returns></returns>
        public int MapURLAndGUID(string lpszURL, ref GUID guidNetworkObject, ref string pcsDesc)
        {
            if (lpszURL == null || lpszURL.Length < 1)
                return 0;

            uint nIndex = 0;
            int hResult = ConnMgrMapURL(lpszURL, ref guidNetworkObject, ref nIndex);
            if (hResult < 0)
            {
                throw new Exception("Could not map a request to a network identifier");
            }
            else
            {
                if (pcsDesc != null)
                {
                    CONNMGR_DESTINATION_INFO DestInfo = new CONNMGR_DESTINATION_INFO();
                    if (ConnMgrEnumDestinations((int)nIndex, ref DestInfo) >= 0)
                    {
                        pcsDesc = DestInfo.szDescription;
                    }
                }
            }

            return (int)nIndex;
        }
        /// <summary>
        /// 枚舉網路標識符資訊
        /// </summary>
        /// <param name="lstNetIdentifiers"></param>
        public List<CONNMGR_DESTINATION_INFO> EnumNetIdentifier()
        {
            List<CONNMGR_DESTINATION_INFO> lstNetIdentifiers = new List<CONNMGR_DESTINATION_INFO>();
            // 得到網路列表
            for (uint dwEnumIndex = 0; ; dwEnumIndex++)
            {
                CONNMGR_DESTINATION_INFO networkDestInfo = new CONNMGR_DESTINATION_INFO();

                if (ConnMgrEnumDestinations((int)dwEnumIndex, ref networkDestInfo) != 0)
                {
                    break;
                }
                lstNetIdentifiers.Add(networkDestInfo);
            }

            return lstNetIdentifiers;
        }

        /// <summary>
        /// 建立串連
        /// </summary>
        /// <param name="nIndex"></param>
        /// <returns></returns>
        public bool EstablishConnection(uint nIndex)
        {
            ReleaseConnection();
            // 得到正確的串連資訊
            CONNMGR_DESTINATION_INFO DestInfo = new CONNMGR_DESTINATION_INFO();
            int hResult = ConnMgrEnumDestinations((int)nIndex, ref DestInfo);

            if (hResult >= 0)
            {
                // 初始化串連結構
                CONNMGR_CONNECTIONINFO ConnInfo = new CONNMGR_CONNECTIONINFO();

                ConnInfo.cbSize = (uint)Marshal.SizeOf(ConnInfo);
                ConnInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
                ConnInfo.dwFlags = CONNMGR_FLAG_PROXY_HTTP | CONNMGR_FLAG_PROXY_WAP | CONNMGR_FLAG_PROXY_SOCKS4 | CONNMGR_FLAG_PROXY_SOCKS5;
                ConnInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
                ConnInfo.guidDestNet = DestInfo.guid;
                ConnInfo.bExclusive = 1;  //0為共用串連,程式退出之後GPRS不關閉;1為不共用
                ConnInfo.bDisabled = 0;

                uint dwStatus = 0;
                hResult = ConnMgrEstablishConnectionSync(ref ConnInfo, ref m_hConnection, 18 * 1000, ref dwStatus);
                if (hResult < 0)
                {
//                    bool bRet = WaitForConnected(10, ref dwStatus);
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return false;
        }
        /// <summary>
        /// 串連狀態
        /// </summary>
        /// <param name="nTimeoutSec"></param>
        /// <param name="pdwStatus"></param>
        /// <returns></returns>
        public bool WaitForConnected(int nTimeoutSec, ref uint pdwStatus)
        {
            uint dwStartTime = GetTickCount();
            bool bRet = false;

            while (GetTickCount() - dwStartTime < (uint)nTimeoutSec * 1000)
            {
                if (m_hConnection.ToInt32() != 0)
                {
                    uint dwStatus = 0;
                    int hr = ConnMgrConnectionStatus(m_hConnection, ref dwStatus);
                    if (dwStatus != 0) pdwStatus = dwStatus;
                    if (hr >= 0)
                    {
                        if (dwStatus == CONNMGR_STATUS_CONNECTED)
                        {
                            bRet = true;
                            break;
                        }
                    }
                }
                Thread.Sleep(100);
            }

            return bRet;
        }

        /// <summary>
        /// 釋放所有串連
        /// </summary>
        public void ReleaseConnection()
        {

            if (m_hConnection.ToInt32() != 0)
            {
                ConnMgrReleaseConnection(m_hConnection, 0);
                m_hConnection = IntPtr.Zero;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct CONNMGR_CONNECTIONINFO
        {
            public uint cbSize;
            public uint dwParams;
            public uint dwFlags;
            public uint dwPriority;
            public int bExclusive;
            public int bDisabled;
            public GUID guidDestNet;
            public IntPtr hWnd;
            public uint uMsg;
            public uint lParam;
            public uint ulMaxCost;
            public uint ulMinRcvBw;
            public uint ulMaxConnLatency;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct CONNMGR_DESTINATION_INFO
        {
            public GUID guid;  // @field GUID associated with network
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONNMGR_MAX_DESC)]
            public string szDescription;  // @field Description of network
            public int fSecure; // @field Is it OK to allow multi-homing on the network
        }

        public struct GUID
        {          // size is 16
            public uint Data1;
            public UInt16 Data2;
            public UInt16 Data3;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] Data4;
        }

        [DllImport("coredll.dll")]
        public static extern uint GetTickCount();

        [DllImport("coredll.dll")]
        public static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);

        [DllImport("cellcore.dll")]
        public static extern int ConnMgrMapURL(string pwszURL, ref GUID pguid, ref uint pdwIndex);

        [DllImport("cellcore.dll")]
        public static extern int ConnMgrEstablishConnectionSync(ref CONNMGR_CONNECTIONINFO ci, ref IntPtr phConnection, uint dwTimeout, ref uint pdwStatus);

        [DllImport("cellcore.dll")]
        private static extern IntPtr ConnMgrApiReadyEvent();

        [DllImport("cellcore.dll")]
        public static extern int ConnMgrReleaseConnection(IntPtr hConnection, int bCache);

        [DllImport("cellcore.dll")]
        public static extern int ConnMgrEnumDestinations(int nIndex, ref CONNMGR_DESTINATION_INFO pDestInfo);

        [DllImport("cellcore.dll")]
        public static extern int ConnMgrConnectionStatus(IntPtr hConnection,    // @parm Handle to connection, returned from ConnMgrEstablishConnection
            ref uint pdwStatus       // @parm Returns current connection status, one of CONNMGR_STATUS_*
            );

        [DllImport("coredll.dll")]
        private static extern int CloseHandle(IntPtr hObject);
    };

 

軟體下載如下: (在叉叉上點右鍵另存新檔MatchTime.exe,去掉.jpg即可)

 

另外具體工程和代碼下載已傳至csdn,正在驗證,隨後貼出來與大家分享!

串連查詢時間伺服器獲得時間和設定系統時間的代碼略過,詳見我上一篇blog

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/ppCuda/archive/2010/01/03/5123011.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.