[Reprinted] [translation] using the rapi library to operate mobile devices-C # language description

Source: Internet
Author: User

Note: This article is original, allCodeAre all taken from your own editedProgramTo ensure compilation. PS, Microsoft's FrontPage 2003 is still very annoying. It took me two hours to create a redundant garbage code.

Content on this page
● Introduction
● Smartphone SDK api library
● Manage directory files in the device
● Retrieve System Information
● Remote operation and text message Functions

Windows Mobile is becoming increasingly mature, and the developer team is growing. As a computer enthusiast and programmer for over 10 years, I cannot resist the temptation of new technologies, and I have moved on to Mobile. The kinship between mobile and Windows determines the popularity of mobile programmers. You can search for mobile apps andArticleCountless. However, for me who plan to develop an all-around desktop <=> device synchronization Management Program, however, we found that the resources were poor-only a bit of information was found on msdn and two foreign developer websites. I am still studying search. Here I want to write a little bit of my experience so far, hoping to help others. In addition, please correct yourself.

Mobile's development resources are complex. Many people often cannot figure out which tools should be installed to build a proper development environment. However, I believe that Microsoft smartphone 2003 SDK and Microsoft pocketpc 2003 SDK are all known and provide essential support for smartphone and pocketpc respectively. Brother, I have not made any achievements so far. I am shy in my pocket and can easily collect a smartphone. Today I already use Microsoft smartphone 2003 SDK as an example.

The smartphone SDK contains a large number of APIs. The list is as follows (from the SDK documentation, translated by myself ):

Smartphone API description
ActiveSync creates mobile application installation and configuration, synchronizes service modules, filters, and assists in accessing applications of the ActiveSync service.
The Bluetooth API creates mobile applications that support Bluetooth devices, such as headphones, printers, and other mobile devices.
Ce messaging (cemapi) Create messaging applications
Configuration Service Providers: create applications that can be configured with various CSPs (configuration service providers)
Connection Manager creates applications that can automatically manage network connections of mobile devices.
Control API uses the smartphone control in your mobile apps
Device management API to create applications that can remotely access mobile device configuration management
Game API (GAPI) creates high-performance real-time games
Home screen API create user interface plug-in
HTML control: Create an application that can display HTML text and embedded images, parse XML and bind URLs to aliases
MIDI: An application for creating playable MIDI files
Object Exchange (obex) creates an object exchange application, allowing mobile devices to freely exchange data via wireless
Pocket outlook Object Model (poom) API creates mobile applications that can operate inbox components (contacts, calendars, and tasks)
Projects control: Create an application that can interact with projects control.
Remote API (rapi) Creates Desktop applications that can synchronize or control mobile devices
Speech recognizer adds speech recognition functions (such as voice dialing) to applications)
Telephony creates applications that support telephone and text messages
User Interface Management Input Panel, add user interface elements to your mobile application
Vibrate API adds the vibration feature to your mobile apps
Voice Recorder control creates a mobile digital recording program
Windows user interface controls creates an application that combines mobile extensions into standard Microsoft Windows CE user interface controls

To create a desktop <=> device's desktop synchronization management program, you mainly rely on the Remote API (rapi) in the sdk api ). The rapi library consists of a group of functions that can be used to manage devices, including directory files, registry and system information of devices, through desktop applications. Let's take a look at how to manage directory files on the device.

Rapi provides a set of file management methods (incomplete list. For details, see the SDK documentation. (Translated by myself ):

Function Description
Copy files in cecopyfile
Cecreatedirectory
Create cecreatefile to open files, pipelines, communication resources, disk devices, or the console. Returns a handle to access the object.
Cedeletefile: delete an object
Cefindallfiles obtains information about all files and directories from the specified Windows CE directory, and copies the information to an array containing the ce_find_data structure.
Cefindfirstfile searches for a file matching the given file name in the directory
Cefindclose closes the specified search handle. The cefindfirstfile and cefindnextfile functions use this handle to search for files.
Cefindnextfile continues searching for files from the last accessed cefindfirstfile
Cegetfileattributes returns the attributes of the specified file or directory.
Cegetfilesize: obtains the size of the specified file in bytes.
Cegetfiletime: Obtain the file creation date and time, last access date and last modification date and time.
Cemovefile: Move (rename) a file or directory
Cereadfile reads file data from the file pointer
Cewritefile writes file data from the file pointer

First, you must initialize the connection to the device for any rapi operation:

Function Description
Cerapiinit (rapi) creates Windows CE Remote Application-Programming Interface (rapi ).
[C #. Net] using system;
Using system. runtime. interopservices; public class rapi
{
Public void rapiinit ()
{
Int ret = cerapiinit ();

If (Ret! = 0)
{
// Connection failed. Failed code Retrieval
Int e = cerapigeterror ();

// Throw an exception
Marshal. throwexceptionforhr (RET );
}

// Connection successful
// To do

}

[Dllimport ("rapi. dll", charset = charset. Unicode)]
Internal static extern int cerapigeterror ();

[Dllimport ("rapi. dll", charset = charset. Unicode)]
Internal static extern int cerapiinit ();
}
 

After the connection is established, you can perform file operations. Let's look at an example of copying a file to a device:

[C #. Net] using system;
Using system. runtime. interopservices;
Using system. IO; public class rapi
{
Private const uint generic_write = 0x40000000; // set the read/write permission
Private const short create_new = 1; // create a new file
Private const short file_attribute_normal = 0x80; // set file attributes
Private const short invalid_handle_value =-1; // error handle

Intptr remotefile = intptr. zero;
String localfilename = @ "C: \ test.txt"; // name of the local computer file
String remotefilename = @ "\ My Documents \ test.txt"; // remote device file name
Byte [] buffer = new byte [0x1000]; // transmission buffer is defined as 4 K
Filestream localfile;

Int bytesread = 0;
Int byteswritten = 0;
Int filepos = 0;

Public rapifile ()
{
// Create a Remote File
Remotefile = cecreatefile (remotefilename, generic_write, 0, 0, create_new,
File_attribute_normal, 0 );

// Check whether the file is successfully created
If (INT) remotefile = invalid_handle_value)
{
Throw new exception ("cocould not create Remote File ");
}

// Open a local file
Localfile = new filestream (localfilename, filemode. Open );

// Read 4 K bytes
Bytesread = localfile. Read (buffer, filepos, buffer. Length );
While (bytesread> 0)
{
// Move the file pointer to the read location
Filepos + = bytesread;

// Write the buffer data to the remote device file
If (! Convert. toboolean (cewritefile (remotefile, buffer, bytesread,
Ref byteswritten, 0 )))
{// Check whether the file handle is successfully closed. An exception is thrown.
Ceclosehandle (remotefile );
Throw new exception ("cocould not write to remote file ");
}
Try
{
// Refill the Local Buffer
Bytesread = localfile. Read (buffer, 0, buffer. Length );
}
Catch (exception)
{
Bytesread = 0;
}
}

// Close the local file
Localfile. Close ();

// Close remote files
Ceclosehandle (remotefile );
}
// Declare the API to be referenced
[Dllimport ("rapi. dll", charset = charset. Unicode)]
Internal static extern int ceclosehandle (intptr hobject );

[Dllimport ("rapi. dll", charset = charset. Unicode)]
Internal static extern int cewritefile (intptr hfile, byte [] lpbuffer,
Int nnumberofbytestowrite, ref int lpnumberofbyteswritten, int lpoverlapped );

[Dllimport ("rapi. dll", charset = charset. Unicode, setlasterror = true)]
Internal static extern intptr cecreatefile (
String lpfilename,
Uint dwdesiredaccess,
Int dww.mode,
Int lpsecurityattributes,
Int dwcreationdisposition,
Int dwflagsandattributes,
Int htemplatefile );
}

After the operation is completed, you need to disconnect the rapi when appropriate. Use the following function (from the SDK documentation, translated by myself ):

Function Description
Cerapiuninit (rapi) Destroys Windows CE Remote Application-Programming Interface (rapi ).
[C #. Net]
Using system;
Using system. runtime. interopservices;

Public class rapiuninit {
Public rapiuninit ()
{
Cerapiuninit ();
}
 
// Declare the API to be referenced
[Dllimport ("rapi. dll", charset = charset. Unicode)]
Internal static extern int cerapiuninit ();
}

There are many file operation functions, and the basic idea is the same. Here we will not give an example one by one. Note that the file handle must be released after use.

Let's look at another example of getting system information. rapi provides some functions for getting system information (from the SDK documentation, translated by myself ):

Function Description
Cegetsysteminfo returns the current system information
Cegetsystemmetrics obtains the size and system settings of Windows elements.
Cegetversionex
Cegetsystempowerstatusex obtains the battery status
Ceglobalmemorystatus
Cegetstoreinformation: Obtain the storage Information and enter the store_information structure.
[C #. Net] public class rapi
{
System_info Si; // system information
Osversioninfo versioninfo; // version information
System_power_status_ex powerstatus; // power supply information
Memorystatus MS; // memory information
String Info;

Public void systeminfo ()
{
// Retrieve System Information
Try
{
Cegetsysteminfo (Out Si );
}
Catch (exception)
{
Throw new exception ("error retrieving system info .");
}

// Retrieve the OS version number of the device.
Bool B;
Versioninfo. dwosversioninfosize = marshal. sizeof (typeof (osversioninfo); // set it to the structure size

B = cegetversionex (Out versioninfo );
If (! B)
{
Throw new exception ("error retrieving version information .");
}

// Retrieve the power status of the device
Try
{
Cegetsystempowerstatusex (Out powerstatus, true); // true indicates to read the latest power supply information; otherwise, it will be obtained from the cache.
}
Catch (exception)
{
Throw new exception ("error Retrieving System Power status .");
}

// Retrieve the device memory status
Ceglobalmemorystatus (Out MS );

// set the search information format.
info = "the connected device has an";
switch (SI. wprocessorarchitecture)
{< br> case processorarchitecture. intel:
info + = "Intel processor. \ n ";
break;
case processorarchitecture. MIPs:
info + = "MIPS processor. \ n ";
break;
case processorarchitecture. arm:
info + = "ARM processor. \ n ";
break;
default:
info =" unknown Processor type. \ n ";
break;
}

Info + = "OS version:" + versioninfo. dwmajorversion + "." + versioninfo. dwminorversion + "." +
Versioninfo. dwbuildnumber + "\ n ";
If (powerstatus. aclinestatus = 1)
{
Info + = "on AC power: Yes \ n ";
}
Else
{
Info + = "on AC power: NO \ n ";
}
Info + = "battery level:" + powerstatus. batterylifepercent + "% \ n ";
Info + = "total memory:" + String. Format ("{0: ####,######}", ms. dwtotalphys) +
"\ N ";

// Display the result.
Console. writeline (Info );
}

# Region declares an API. For details, see the SDK documentation.
[Dllimport ("rapi. dll", charset = charset. Unicode, setlasterror = true)]
Internal static extern int cegetsysteminfo (Out system_info psi );

[Dllimport ("rapi. dll", charset = charset. Unicode, setlasterror = true)]
Internal static extern bool cegetversionex (Out osversioninfo lpversioninformation );

[Dllimport ("rapi. dll", charset = charset. Unicode, setlasterror = true)]
Internal static extern bool cegetsystempowerstatusex (Out system_power_status_ex pstatus, bool fupdate );

[Dllimport ("rapi. dll", charset = charset. Unicode, setlasterror = true)]
Internal static extern void ceglobalmemorystatus (Out memorystatus MSCE );
# Endregion

# Region declaration Structure
///
/// CPU architecture (cegetsysteminfo)
///
Public Enum processorarchitecture: short
{
///
/// Intel
///
Intel = 0,

///
/// MIPS
///
MIPs = 1,

///
/// Alpha
///
Alpha = 2,

///
/// Powerpc
///
PPC = 3,

///
/// Hitachi shx
///
Shx = 4,

///
/// Arm
///
Arm = 5,

///
/// IA64
///
IA64 = 6,

///
/// Alpha 64
///
Alpha64 = 7,

///
/// Unknown
///
Unknown =-1
}

///
/// Memory information of mobile devices
///
[Structlayout (layoutkind. Sequential)]
Public struct memorystatus
{
Internal uint dwlength;
///
/// Current memory usage (%)
///
Public int dwmemoryload;
///
/// Total physical memory
///
Public int dwtotalphys;
///
/// Available physical memory
///
Public int dwavailphys;
///
/// Page number
///
Public int dwtotalpagefile;
///
/// Not paging
///
Public int dwavailpagefile;
///
/// Total virtual memory
///
Public int dwtotalvirtual;
///
/// Available virtual memory
///
Public int dwavailvirtual;
}

///
/// Mobile device power information
///
Public struct system_power_status_ex
{
///
/// AC status
///
Public byte aclinestatus;
///
/// Battery charging status. 1 High, 2 low, 4 critical, 8 charging, 128 no system battery, 255 Unknown Status
///
Public byte batteryflag;
///
/// Percentage of remaining battery power
///
Public byte batterylifepercent;
///
/// Reserved field, set to 0
///
Internal byte reserved1;
///
/// Remaining battery power time (seconds)
///
Public int batterylifetime;
///
/// Total battery available time (seconds)
///
Public int batteryfulllifetime;
///
/// Reserved field, set to 0
///
Internal byte reserved2;
///
/// Backup battery status
///
Public byte backupbatteryflag;
///
/// Percentage of remaining battery in reserve
///
Public byte backupbatterylifepercent;
///
/// Reserved field, set to 0
///
Internal byte reserved3;
///
/// Remaining time of battery backup (seconds)
///
Public int backupbatterylifetime;
///
/// The total available time (in seconds) of the battery backup)
///
Public int backupbatteryfulllifetime;
}

///
/// Osversioninfo platform type
///
Public Enum platformtype: int
{
///
/// Win32 on Windows CE.
///
Ver_platform_win32_ce = 3
}

///
/// Operating system version information
///
Public struct osversioninfo
{
Internal int dwosversioninfosize;
///
/// Main version information
///
Public int dwmajorversion;
///
/// Sub-version information
///
Public int dwminorversion;
///
/// Compilation Information
///
Public int dwbuildnumber;
///
/// Operating system type
///
Public platformtype dwplatformid;
}

///
/// Processor type (cegetsysteminfo)
///
Public Enum processortype: int
{
///
/// 386
///
Processor_intel_386 = 386,
///
/// 486
///
Processor_intel_timeout = 486,
///
/// Pentium
///
Processor_intel_pentium = 586,
///
/// P2
///
Processor_intel_pentiumii = 686,
///
/// Ia 64
///
Processor_intel_ia64= 2200,
///
/// MIPS 4000 Series
///
Processor_mips_r4000 = 4000,
///
/// Alpha 21064
///
Processor_alpha_21064= 21064,
///
/// PowerPC 403
///
Processor_ppc_403 = 403,
///
/// PowerPC 601
///
Processor_ppc_601. = 601,
///
/// PowerPC 603
///
Processor_ppc_603 = 603,
///
/// PowerPC 604
///
Processor_ppc_604 = 604,
///
/// PowerPC 620
///
Processor_ppc_620 = 620,
///
/// Hitachi SH3
///
Processor_hitachi_sh3 = 10003,
///
/// Hitachi sh3e
///
Processor_hitachi_sh 3E = 10004,
///
/// Hitachi sh4
///
Processor_hitachi_sh4 = 10005,
///
/// Motorola 821
///
Processor_policla_821 = 821,
///
/// Hitachi SH3
///
Processor_shx_sh3 = 103,
///
/// Hitachi sh4
///
Processor_shx_sh4 = 104,
///
/// Intel strongarm
///
Processor_strongarm = 2577,
///
/// Arm720
///
Processor_arm720 = 1824,
///
/// Arm820
///
Processor_arm820 = 2080,
///
/// Arm920
///
Processor_arm920 = 2336,
///
/// ARM 7
///
Processor_arm_7tdmi = 70001
}

///
/// Data structure of cegetsysteminfo
///
Public struct system_info
{
///
/// Processor Architecture
///
Public processorarchitecture wprocessorarchitecture;
///
/// Reserved
///
Internal ushort wreserved;
///
/// Specifies the page size and the granularity of page protection and commitment.
///
Public int dwpagesize;
///
/// Minimum value of the memory address that the application can access
/// (Pointer to the lowest memory address accessible to applications
/// And dynamic-Link Libraries (DLLs ).)
///
Public int lpminimumapplicationaddress;
///
/// Maximum memory address accessible to the application (pointer to the highest memory address)
/// Accessible to applications and DLLs .)
///
Public int lpmaximumapplicationaddress;
///
/// Specifies a mask representing the set of processors configured
/// The system. Bit 0 is processor 0; bit 31 is processor 31.
///
Public int dwactiveprocessormask;
///
/// Number of processors (specifies the number of processors in the system .)
///
Public int dwnumberofprocessors;
///
/// Specifies the type of processor in the system .)
///
Public processortype dwprocessortype;
///
/// Specifies the granularity with which virtual memory is allocated.
///
Public int dwallocationgranularity;
///
/// Specifies the system architecture-dependent processor level.
///
Public short wprocessorlevel;
///
/// Specifies an architecture-dependent processor revision.
///
Public short wprocessorrevision;
}
# Endregion
}

There are many other things that rapi can do, such as obtaining registry information, providing access to the underlying functions of Microsoft ActiveSync, running remote applications, and file lists. It is not difficult to read the SDK documentation carefully.

As the Desktop Management Program of mobile devices, it is essential to back up call records and send SMS messages online. When I first discovered rapi, I thought there were ready-made functions to use like the previous example. After careful research, we can find that it is much more complicated. I believe this is a function that many of my friends hope to implement. Therefore, I would like to explain it as follows.

Rapi does not provide call, SIM card, and SMS functions. They are included in the phone API, Sim manager, and short message service of the smartphone SDK. However, the phone that contains these Apis. DLL, cellcore. DLL and SMS. DLL files are stored on devices. programs running on Windows cannot call dynamic connection libraries stored on remote devices.

We still need rapi. Although it does not provide direct access to call records and SMS operations, it provides a special function:

Function Description
Cerapiinvoke uses a common mechanism to execute remote programs.

The prototype of cerapiinvoke is as follows:

Stdapi _ (hresult) cerapiinvoke (
Lpcwstr pdllpath, // The complete path of the DLL file containing the API
Lpcwstr pfunctionname, // name of the function to be called
DWORD cbinput, // function input buffer size
Byte * pinput, // function input buffer pointer
DWORD * pcboutput, // function output buffer size
Byte ** ppoutput, // function output buffer pointer
Irapistream ** ppirapistream, // specify the blocking mode or stream mode
DWORD dwreserved); // Reserved

Cerapiinvoke will allow us to call any API functions on the remote device! Instead of calling the API directly, you still need to "package" The Remote API ". Due to the time relationship, I will give you a detailed description of cerapiinvoke in the near future.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/jarvisj/archive/2005/06/05/387902.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.