読者です 読者をやめる 読者になる 読者になる

酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Windows MobileでSIMの電話番号を取得する

Windows Mobile

P/Invoke経由でSIMの電話番号を取得します。「合成確率 WindowsMobileで、SIMの電話番号を取得する (VB.net)」を参考にしました。

Imports System.Runtime.InteropServices 
Imports interopserv = System.Runtime.InteropServices 
Imports System 
Imports System.ComponentModel

Public Enum SMS_ADDRESS_TYPE 
    SMSAT_UNKNOWN = 0 
    SMSAT_INTERNATIONAL 
    SMSAT_NATIONAL 
    SMSAT_NETWORKSPECIFIC 
    SMSAT_SUBSCRIBER 
    SMSAT_ALPHANUMERIC 
    SMSAT_ABBREVIATED 
End Enum 'SMS_ADDRESS_TYPE

Public Structure PhoneAddress  
      Public AddressType As SMS_ADDRESS_TYPE  
       Public Address() As Char 
End Structure

Class Sim 
    Private Class WinApi

        Public Const LMEM_FIXED As Long = 0 
        Public Const LMEM_MOVEABLE As Long = 2 
        Public Const LMEM_ZEROINIT As Long = &H40 
        Public Const LPTR As Long = LMEM_FIXED Or LMEM_ZEROINIT


        <System.Runtime.InteropServices.DllImport("coredll.dll", SetLastError:=True)> _ 
        Public Shared Function LocalAlloc(ByVal uFlags As System.Int32, ByVal uBytes As System.Int32) As IntPtr 
        End Function

    End Class

    Public Shared Function AllocHLocal(ByVal cb As Int32) As IntPtr 
        Try 
            Return WinApi.LocalAlloc(WinApi.LPTR, cb) 
        Catch ex As Exception 
        End Try 
    End Function


    Private Shared SERVICE_PROVIDER As Long = &H6F46

    <StructLayout(LayoutKind.Sequential)> _ 
    Public Structure SimRecord 
        Public cbSize As IntPtr 
        Public dwParams As IntPtr 
        Public dwRecordType As IntPtr 
        Public dwItemCount As IntPtr 
        Public dwSize As IntPtr 
    End Structure

    <System.Runtime.InteropServices.DllImport("sms.dll")> _ 
    Private Shared Function SmsGetPhoneNumber(ByVal psmsaAddress As IntPtr) As IntPtr 
    End Function


    ' Gets the phone number from the SIM. 
    Public Shared Function GetPhoneNumber() As String 
        Dim phoneaddr As PhoneAddress = New PhoneAddress 
        Dim buffer(512) As Byte 
        Dim pAddr() As Byte = buffer 
        Dim ipAddr As IntPtr = AllocHLocal(pAddr.Length) 
        Dim res As IntPtr = IntPtr.Zero

        Try 
            res = SmsGetPhoneNumber(ipAddr) 
        Catch ex As Exception 
            MessageBox.Show(ex.Message) 
        End Try

        If (res.ToInt32 <> 0) Then 
            Return Nothing 
        End If

        phoneaddr.AddressType = System.Runtime.InteropServices.Marshal.ReadInt32(ipAddr)

        ipAddr = IntPtr.op_Explicit(System.Runtime.InteropServices.Marshal.SizeOf(phoneaddr.AddressType) + ipAddr.ToInt32) 
        phoneaddr.Address = System.Runtime.InteropServices.Marshal.PtrToStringUni(ipAddr)

        Return phoneaddr.Address 
    End Function


End Class 

参考