The Big Red Toolbox

MGCEWin32

A collection of handy system calls, including the Registry, the clipboard, the icon tray, timer and much more.

December 13, 1999

© NSB Corporation. All rights reserved.


MGCEWin32 - Windows CE Custom Control Objects
Written by Mark Gamber, October 1999

NS Basic is (c) NS Basic Corporation
Windows CE is (c) Microsoft Corporation

MGCEWin32 provides four separate controls for Windows CE applications capable of making use of COM oriented controls such as NS Basic. Included in this package are:

Installation

Connect your Windows CE device to your desktop using ActiveSync. On the desktop, run the program MGCEWin32.exe. Follow the instructions on the screen to complete the installation. All four controls will be installed and registered automatically.


API Control

There are hundreds of available functions in the Win32 API as implemented on Windows CE devices. Unfortunately, none of them are directly available from Basic. Visual Basic can access the functions using the "declare" statement, but it's not terribly intuitive and other brands of Basic may not be able to access the API at all. While it is impractical to provide access to every API function available, it is practical to provide access to the most commonly used and useful functions in the Win32 API which is what this object does. In addition, Windows CE sends messages to applications when certain system-wide changes or events take place. The API control catches these messages and turns them into events your application can handle if it so chooses. Note that the object does not attempt to protect the system from errant programming, so be careful when using this control!

The number of possible flags, options and messages available to even the limited subset of functions this object supports is large enough that this document does not list them, nor does it provide a tutorial of the Win32 API and its use. If you are not familiar with the Win32 API, it is strongly suggested that you do NOT use this object until you have become familiar with the API and the calls supported by this object. While its extremely unlikely that physical damage could occur to your device by using the API, it can't be ruled out and it is entirely possible to lock up a device, requiring a cold reset, using the API. You have been warned and have already agreed, by installing the object, that you accept full responsibility for the use of this object and may not hold the object's author or any distributor of the object liable for any loss or damage brought about by the use of the object.

Object Creation

AddObject "MGCEWin32.API", "Name"

Samples

Properties

Capture Set and retrieve the window handle that has captured input focus. See the ReleaseCapture method to release input capture once it has been set.
API.Capture = lWnd
lWnd = API.Capture
ClassName Read only. ClassName retrieves the text name of a specified window's class.
MsgBox API.ClassName( lWnd )
ClipText Set and retrieve plain text to and from the system clipboard.
API.ClipText = "Add something to the clipboard"
sText = API.ClipText
CursorPos Retrieve the X,Y coordinates of the cursor when the cursor was last used. This property returns an array of two values, the first being the horizontal position and the second being the vertical position.
aPos = API.CursorPos
x = aPos( 1 )
y = aPos( 2 )
EnableKeyboard TRUE enables the device keyboard, FALSE disables the device keyboard.
API.EnableKeyboard = FALSE
iKeyStatus = API.EnableKeyboard
Focus Set and retrieve the window handle with input focus.
API.Focus = lWnd
lWnd = API.Focus
ForegroundWindow Set and retrieve the current foreground window.
API.ForegroundWindow = lWnd
lWnd = API.ForegroundWindow
GetShortcutTarget Read only. You may retrieve the file a shortcut points to using this property.
s = API.GetShortcutTarget "My Link.lnk"
GetWindow Read only. This property retrieves the handle of a window based on a window specified and a relationship flag. These flags are:
  • WNDFIRST (0): Retrieve the first peer window of the window specified.
  • WNDLAST (1): Retrieve the last peer window of the window specified.
  • WNDNEXT (2): Retrieve the next peer window of the window specified.
  • WNDPREV (3): Retrieve the previous peer window of the window specified.
  • WNDOWNER (4): Retrieve the owner (parent) of the specified window.
  • WNDCHILD (5): Retrieve the first child window of the window specified.
lChild = API.GetWindow( lWnd, WNDCHILD )
LocalTime Set and retrieve the current time and date according to the locale specified by the Windows CE device.
d = API.LocalTime
API.LocalTime = Now
SystemColor Set and retrieve RGB color values for system components. Note: Changes made using this property are temporary and are not maintained when a device is restarted. SystemColor flags are:
  • colorScrollBar: 0
  • colorBackground: 1
  • colorActiveCaption: 2
  • colorInactiveCaption: 3
  • colorMenu: 4
  • colorWindow: 5
  • colorWindowFrame: 6
  • colorMenuText: 7
  • colorWindowText: 8
  • colorCaptionText: 9
  • colorActiveBorder: 10
  • colorInactiveBorder: 11
  • colorAppWorkspace: 12
  • colorHighlight: 13
  • colorHighlightText: 14
  • colorBtnFace: 15 colorBtnShadow: 16
  • colorGrayText: 17
  • colorBtnText: 18
  • colorInactiveCaptionText:
  • colorBtnHighlight: 20
  • color3DDKShadow: 21
  • color3DLight: 22
  • colorInfoText: 23
  • colorInfoBK: 24
clr = API.SystemColor( colorWindow )
API.SystemColor( colorBackground ) = (128 * 65536 )
SystemParameters This property sets and retrieves various system-wide values which may or may not be supported by a given version of Windows CE. Values supported by the control are:
  • spWorkArea: 0
  • spWakupIdleTimeout: 1
  • spExternalIdleTimeout: 2
  • spBatteryIdleTimeout: 3
  • spPlatformType: 4
  • spOEMInfo: 5
The first four values are numeric, the last two are strings and read only.

iTurnOffTime = API.SystemParameters( spBatteryIdleTimeout ) API.SystemParameters( spBatteryIdleTimeout ) = 180 ' 3 minutes
SystemVersion Retrieves the version of Windows CE. The upper 2 bytes of the returned value is the major version number and the lower 2 bytes of the value is the minor version number.

version = API.SystemVersion
SystemTime Set and retrieve the system time and date. Note that the time is specified in Universal Coordinated Time (UTC).
d = API.SystemTime
API.SystemTime = Now
Ticks Retrives the number of milliseconds that have elapsed since Windows CE was started.
i = API.Ticks/CODE>
TopMost The TopMost property sets and retrieves a window handle with topmost or "Stay On Top" status. TRUE sets a window to topmost status, FALSE sets the window to normal (not topmost) status.

API.TopMost( lWnd ) = TRUE
iStatus = API.TopMost( lWnd )
WindowLong Set and retrieve long values applied to windows. This may be used to examine and alter window styles and custom data.
i = API.WindowLong( lWnd, -16 ) ' Get window style
API.WindowLong( lWnd, -16 ) = WS_CAPTION ' Apply caption to style
WindowParent Set and retrieve the parent of a specified window.
API.WindowParent( lChild ) = lNewParent
lParent = API.WindowParent( lWnd )
WindowText Set and retrive the text displayed by a window caption. For most windows, this is the text that appears in a caption bar. For other windows, such as edit controls, this is the text that appears within the window itself. API.WindowText( lWnd ) = "Main Window"
sCaption = API.WindowText( lWnd )
Version Return the current version of this control as an integer

Methods

AddToRecent This method creates a link to a specified file in the "Recently used" folder. On most devices, this is the "My Documents" folder.

API.AddToRecent "\somefile.txt"
ChildWindowFromPoint Given the handle of a window and screen coordinate, in pixels, this method will return the handle (if any) of a window at that coordinate which is a child of the specified window.

lChild = API.ChildWindowFromPoint lWnd, xPos, yPos
CreateShortcut Create a shortcut to a specified file on the device.

API.CreateShortcut sShortcutFilename, "\windows" ' Shortcut to Windows dir
FindWindow Returns the handle of a window identified by its caption text. This will not find child windows, only top level windows.

lWnd = API.FindWindow "apitest.nsb"
FindWindowByClass Returns the handle of a window identified by its class name. This will not find child windows, only top level windows.

lWnd = API.FindWindowByClass "MyWndClass"
GetAsyncKeyState Retrieve the state of a keyboard key since the last time this method was called.

iKeyState = API.GetAsyncKeyState( 32 ) ' Check on spacebar
GetMemoryStatus Use this method to retrieve one of several available memory status values. Method options are:
  • memTotalPhysical: 0
  • memAvailPhysical: 1
  • memTotalPagefile: 2
  • memAvailPagefile: 3
  • memTotalVirtual: 4
  • memAvailVirtual: 5
  • memLoadPercent: 6
iMemLoad = API.GetMemoryStatus( memLoadPercent )
GetPowerStatus This method retrieves one of several power (AC, Battery, etc) status values which may or may not be supported on a given Windows CE device. Flags include:
  • AC Status: 0
  • Battery Flag: 1
  • Battery Percent: 2
  • Battery Life: 3
  • Battery Full Life: 4
  • Backup Flag: 5
  • Backup Percent: 6
  • Backup Life: 7
  • Backup Full Life: 8
    AC Status return values:
  • ACOffline: 0
  • ACOnline: 1
  • ACUnknown: 255
    Battery Flag / Backup Flag return values:
  • BatteryHigh: 1
  • BatteryLow: 2
  • BatteryCritical: 4
  • BatteryCharging: 8
  • NoBattery: 128
  • BatteryUnknown: 255
iBatteryStatus = API.GetPowerStatus( 0 )
GetSpecialFolder This method retrieves the path of a "special folder", such as Favorites, Desktop and Controls. Most devices support most of the possible flags, most they are not all supported on all devices and will return an empty string (""). Flags include:
  • sfDesktop: 0
  • sfPrograms: 2
  • sfControls: 3
  • sfPrinters: 4
  • sfPersonal: 5
  • sfFavorites: 6
  • sfStartup: 7
  • sfRecent: 8
  • sfSendTo: 9
  • sfRecycler: 10
  • sfStartMenu: 11
  • sfDesktopDir: 16
  • sfDrives: 17
  • sfNetwork: 18
  • sfNetHood: 19
  • sfFonts: 20
  • sfTemplates: 21
sPath = API.GetSpecialFolder( sfDesktop )
GetStorageStatus Retrieve the memory status of program storage. Flags include:
  • Storage Total Size: 0
  • Storage Free Size: 1
iBytesFree = API.GetStorageStatus( 1 )
PostMessage This method posts a message to a window.

iReturnVal = API.PostMessage( lWnd, msg, wParam, lParam )
ReleaseCapture Release input capture. If input capture was not set, nothing happens.

API.ReleaseCapture
SendKeys Send keystrokes to whatever window has input focus at the time this method is called. Shift, Control and Alt keystrokes causes the control to toggle an internal flag. When any of these three keys are sent, the flag is set and all keystrokes following are sent as though the Shift, Control or Alt key is being pressed at the same time. When sent again, the flag is reset and following keystrokes are sent as though the Shift, Control or Alt key is NOT pressed at the same time. This continues through the string of keys passed to this method. A second parameter determines if "key clicks" are used and should be set to TRUE for silent operation or FALSE for key clicks.

API.SendKeys Chr(16) & "T" & Chr(16) & "est", FALSE
SendMessage Sends a message to a window. Since SendMessage can pass numeric values or strings, this method is used to send a numeric (32 bit) value with the message.

iReturnVal = API.SendMessage( lWnd, msg, wParam, lParam )
SendMessageText This method also sends a message to a window. Unlike SendMessage, the last parameter of this method is a string which is sent with the message.

iRetVal = API.SendMessageText( lWnd, msg, wParam, "Item text" )
showWindow A window may be hidden, displayed, minimized and otherwise using this method. Note the lowercase "s" in showWindow is not a typo! Flags include:
  • swHide: 0
  • swShowNormal: 1
  • swShowNoActivate:4
  • swShow: 5
  • swMinimize: 6
  • swShowMaximized: 11
  • swMaximize: 12
  • swRestore: 13
API.showWindow lWnd, swHide
WindowFromPoint This method will find a top level window at a specified screen coordinate and return its handle, if any.

lWnd = API.WindowFromPoint( xPos, yPos )

Events

ColorChange This event is triggered when an application changes a system wide color.
sub API_ColorChange
	MsgBox "Something changed a system color"
end sub
FontChange This event is triggered when an application adds or removes a font resource.
sub API_FontChange
	MsgBox "A font has been added or removed"
end sub
		
Hibernate When the device begins to run low on resources, a hibernate message is sent to all running applications. It is the job of the applications to lower their memory usage by freeing unneeded resources or, if possible, closing.
sub API_Hibernate
	MsgBox "Uh oh...something bad is about to happen"
end sub
		
PaletteChange When an applicate changes the system color palette, this event is fired, allowing a program alter its own color palette if it needs to do so.
sub API_PaletteChange
	MsgBox "The system color palette has been changed"
end sub
		
SettingsChange SystemParameters can get and retrieve various system settings and this event notifies a program when one of those settings has been changed. The value passed to this event is a flag which may be used with SystemParameters in order to retrieve the new value of the setting that was changed.
sub API_SettingsChange( flag )
	val = API.SystemParameters( flag )
end sub
		

Tray Image Control

The Tray Image control provides access to the system tray from Basic and allows you to add images to, removes images from and modify existing images on the system tray. The Tray Image control supports the following properties, methods and events:

Object Creation

AddObject "MGCEWin32.Tray", "Name"

Samples

Properties

Value The Value property is what actually adds, removes and modifies tray images. The image to display is identified by its position in the control's image list. To remove an image from the tray, use zero. To add or modify an image, specify an image number. If an image is not displayed in the tray, one is added.

Tray.Value = 1
iCurImage = Tray.Value
Version Return the current version of this control as an integer

Methods

AddImage The Tray object maintains a list of images, each image identified by the morder in which it was added. The first image added using the AddImage method is image one and so on. Only valid Windows bitmaps are accepted by the tray object and 16 color images are recommended.

Tray.AddImage "\smimg1.bmp"
RemoveImage You may remove images from the image list at any time by specifying the number of the image to remove, starting with one for the first image added to the object.

Tray.RemoveImage 1

Events

Click When a tray image created by the object is tapped, the Click event is fired, passing along the number of the image currently displayed. A basic event handler can catch and make use of this event.
sub Tray_Click( image )
	MsgBox "You tapped image #" & CStr( image )
end sub

Registry Control

The Registry control provides a very flexible way to access the Windows CE registry from Basic. The registry control DOES NOT attempt to protect the registry from errant programming, however, so exercise caution when modifying the registry. The Registry Control supports the following properties, methods and events:

Object Creation

AddObject "MGCEWin32.Registry", "Name" H4>Samples

Properties

Key The Key property sets and retrieves the "base key" from which path operations take place. There are four valid key values:
  • CLASSES_ROOT: 0
  • CURRENT_USER: 1
  • LOCAL_MACHINE: 2
  • USERS: 3
Registry.Key = 1
iCurKey = Registry.Key
Path Use the Path property to set and retrieve the current path into the registry. This value is combined with the Key property to make a full path into a specified section of the registry.

Registry.Path = "Software\MyApp"
sPath = Registry.Path
Name The Name property identifies a value name in the registry. If the value does not exist when reading from the registry, an error occurs and may be trapped by using the "on error resume next" line to prevent the error from stopping the program and using the "Err.Number" variable to determine if an error occurred. When writing to the registry and the value doesn't exist, it is created as a type specified by the ValueType property.

Registry.Name = "MyData"
sName = Registry.Name
ValueType Set and retrieve the type of value currently being read or written from or to the registry. Four types are supported by the registry object including:
  • REG_SZ (1): Text string
  • REG_BINARY (3): Binary data
  • REG_DWORD (4): 32 bit numeric value
  • REG_MULTI_SZ (7): An array of text strings
Various implementations of Basic may or may not support single byte binary data manipulation. To ensure that the data may be used from within Basic, Binary data is written and read as a string of hexidecimal data. When the Key, Path and Name properties combine to point to an existing value, that value's data type may be obtained by reading this property.

Registry.ValueType = 4
ValType = Registry.ValueType
Value Set and retrieve data to and from the registry using the Value property. You must set the Key, Path and Name properties before reading or writing from or to the registry usng this property. Because registry data comes in many forms (text, numeric, array and binary formats), the Value property does automatic conversion when possible. It cannot convert any type to Binary or Array values, not can it convert Binary or Array values to any type.
Registry.ValueType = REG_DWORD
Registry.Value = "32"      ' This will convert to the number 32
Registry.ValueType = REG_SZ
Registry.Value = 150       ' This will convert to the string "150"
Registry.ValueType = REG_BINARY
Registry.Value = "FFFF00FF0A0B0C0D"  ' Add a binary value
Registry.ValueType = REG_MULTI_SZ  ' Add a string array
a = Array( 2, 3, "Four", 5 )       ' Numbers will convert to strings
Registry.Value = a
a = Registry.Value    ' When reading an array, you can
if Registry.ValueType = REG_MULTI_SZ then ' determine the number of
	iItem = UBound( a )        ' items read by using UBound()
end if
Version Return the current version of this control as an integer

Methods

CreatePath The current Key and Path properties are combined to form a path into the registry. Set these two properties and call CreatePath to create a new path. If the path already exists, it is not modified by this method.

Registry.Key = CURRENT_USER
Registry.Path = "Software\Test"
Registry.CreatePath
DeletePath Set the current Key and Path properties, then call the DeletePath method to remove a path from the registry.

Registry.Key = CURRENT_USER
Registry.Path = "Software\Test"
Registry.DeletePath
DeleteValue You may set the Key, Path and Name properties and then call the DeleteValue method to remove a value from the registry.

Registry.Key = CURRENT_USER
Registry.Path = "Software\Test"
Registry.Name = "TestVal"
Registry.DeleteValue
GetPathName This method is used to find paths connected to a path specified by the Key and Path properties. For example, if the "CURRENT_USER\Software\Test" path has three paths within it, the may be found by calling this method and starting with one, adding one to the value passed to the method each time it is called until an error occurs.
on error resume next
Registry.Key = CURRENT_USER
Registry.Path = "Software\Test"
iNum = 1
while Err.Number = 0
	MsgBox Registry.GetPathName( iNum )
	iNum = iNum + 1
wend
GetValueName Similar to the GetPathName method except this method hunts for and returns value names. The first value is found by specifying one and following values are found by increasing the number passed to the method with each call until an error occurs.
on error resume next
Registry.Key = CURRENT_USER
Registry.Path = "Software\Test"
iNum = 1
while Err.Number = 0
	MsgBox Registry.GetValueName( iNum )
	iNum = iNum + 1
wend

Events

The registry object does not support any events.

Timer Control

The Timer control is a very simple object you may use to send events to an application on regular intervals. The Timer Control supports the following properties, methods and events:

Object Creation

AddObject "MGCEWin32.Timer", "Name"

Samples

Properties

Interval The number of milliseconds to wait between events. Interval ranges from one to 2147483647.

Timer.Interval = 1000
i = Timer.Interval
Version Return the current version of this control as an integer

Methods

Start Call the Start method to start the timer. If the Interval property was set properly, the application will begin to receive events. Note that starting the timer itself is not an event. The first event occurs after the first specified interval.

Timer.Start
Stop The Stop method stops a running timer. If there is no running timer when Stop is called, nothing happens.

Timer.Stop

Events

Interval The Interval event is triggered when the number of milliseconds specified by the Interval property has passed. The application will receive this event until the timer is stopped or the application is closed.
sub Timer_Interval	
	Listbox.AddItem "Interval fired"
end sub
	

RAS Control

The RAS Control provides access to the remote access API, allowing programs capable of using the object to dial a remote network, hang up a connection, set logon parameters and maintain connections. The RAS control supports the following properties, methods and events:

Object Creation

AddObject "MGCEWin32.RAS", "name"

Samples

Properties

AllConnections Retrieves an array of open connections. If there are no open connections, an empty array is returned. Each item in the array is a 32 bit number which identifies a connection.

a = RAS.AllConnections

AllEntries Retrieves an array of remote access connection names. If there are no names available, an empty array is returned. Each array entry is a string which identifies a connection.

aNames = RAS.AllEntries

ConnectionStatus Retrieve the current state of a connection as a bit field. The connection is identified by a 32 bit value passed to the property. Possible status bits include:

status = RAS.ConnectionStatus( connID )

Domain Set and retrieve a domain name to apply to a remote connection.

sDomain = RAS.Domain
RAS.Domain = "DEVGROUP"

EntryName Set and retrieve the name of a connection to dial.

RAS.EntryName = "WrkServer"
sName = RAS.EntryName

Password Set and retrieve a password used to log into a connection.

RAS.Password = "tritium"
sPwd = RAS.Password

PhoneNumber Set and retrieve a phone number to dial in order to establish a connection. If this property is used, the EntryName property must be cleared ("") and vice versa.

RAS.PhoneNumber = "555-1212"
sNum = RAS.PhoneNumber

UserName Set and retrieve a user name used to log into a connection.

RAS.UserName = "howard"
sName = RAS.UserName

Validate Determine if a connection name is valid. An error occurs is an invalid or existing entry name is passed to this property.

iValid = RAS.Validate( "New Entry" )

Version Retrieve the version of the RAS object.

v = RAS.Version

Methods

Clear Removes all data from the Domain, EntryName, Password, PhoneNumber, UserName and Password properties.

RAS.Clear

Connect This method attempts to connect to a server with data applied using the Domain, EntryName, Password, PhoneNumber, UserName and Password properties. If a valid connection is established, a 32 bit connection identifier is returned by the method. This value may be later used to disconnect.

iConnID = RAS.Connect

DeleteEntry Remove an entry from the device phone book. The entry is identified by name.

RAS.DeleteEntry "New Entry"

Disconnect Hang up a current connection, the connection identified by a 32 bit value assigned by the Connect method or the AllConnections property.

RAS.Disconnect iConnID

GetDialParams The properties associated with a remote access entry may be obtained by specifying the name using the EntryName property and calling the GetDialParams method. The Domain, Password, PhoneNumber and UserName properties are updated with the entry data.

RAS.EntryName = "Work Server"
RAS.GetDialParams

RenameEntry Rename a remote access entry name.

RAS.RenameEntry "OldName", "New Name"

SetDialParams After setting the EntryName, Domain, Password, PhoneNumber and UserName properties, call SetDialParams to save those properties.

RAS.SetDialParams

Events

The RAS object does not support events.

Change Log

10/24/99: Added RAS object

10/24/99: API Object: added cursorPos and SystemVersion properties

11/5/99: API Object: WindowLong added, example for showWindow corrected.

12/13/99: API Object: added LocalTime, SystemTime, Ticks and WindowParent properties