NAME

OS2::Process - exports constants for system() call, and process control on OS2.

SYNOPSIS

use OS2::Process;
$pid = system(P_PM | P_BACKGROUND, "epm.exe");

DESCRIPTION

Optional argument to system()

the builtin function system() under OS/2 allows an optional first argument which denotes the mode of the process. Note that this argument is recognized only if it is strictly numerical.

You can use either one of the process modes:

P_WAIT (0)	= wait until child terminates (default)
P_NOWAIT	= do not wait until child terminates
P_SESSION	= new session
P_DETACH	= detached
P_PM		= PM program

and optionally add PM and session option bits:

P_DEFAULT (0)	= default
P_MINIMIZE	= minimized
P_MAXIMIZE	= maximized
P_FULLSCREEN	= fullscreen (session only)
P_WINDOWED	= windowed (session only)

P_FOREGROUND	= foreground (if running in foreground)
P_BACKGROUND	= background

P_NOCLOSE	= don't close window on exit (session only)

P_QUOTE		= quote all arguments
P_TILDE		= MKS argument passing convention
P_UNRELATED	= do not kill child when father terminates

Access to process properties

On OS/2 processes have the usual parent/child semantic; additionally, there is a hierarchy of sessions with their own parent/child tree. A session is either a FS session, or a windowed pseudo-session created by PM. A session is a "unit of user interaction", a change to in/out settings in one of them does not affect other sessions.

my_type()

returns the type of the current process (one of "FS", "DOS", "VIO", "PM", "DETACH" and "UNKNOWN"), or undef on error.

file_type(file)

returns the type of the executable file file, or dies on error. The bits 0-2 of the result contain one of the values

T_NOTSPEC (0)

Application type is not specified in the executable header.

T_NOTWINDOWCOMPAT (1)

Application type is not-window-compatible.

T_WINDOWCOMPAT (2)

Application type is window-compatible.

T_WINDOWAPI (3)

Application type is window-API.

The remaining bits should be masked with the following values to determine the type of the executable:

T_BOUND (8)

Set to 1 if the executable file has been "bound" (by the BIND command) as a Family API application. Bits 0, 1, and 2 still apply.

T_DLL (0x10)

Set to 1 if the executable file is a dynamic link library (DLL) module. Bits 0, 1, 2, 3, and 5 will be set to 0.

T_DOS (0x20)

Set to 1 if the executable file is in PC/DOS format. Bits 0, 1, 2, 3, and 4 will be set to 0.

T_PHYSDRV (0x40)

Set to 1 if the executable file is a physical device driver.

T_VIRTDRV (0x80)

Set to 1 if the executable file is a virtual device driver.

T_PROTDLL (0x100)

Set to 1 if the executable file is a protected-memory dynamic link library module.

T_32BIT (0x4000)

Set to 1 for 32-bit executable files.

file_type() may croak with one of the strings "Invalid EXE signature" or "EXE marked invalid" to indicate typical error conditions. If given non-absolute path, will look on PATH, will add extension .exe if no extension is present (add extension . to suppress).

@list = process_codepages()

the first element is the currently active codepage, up to 2 additional entries specify the system's "prepared codepages": the codepages the user can switch to. The active codepage of a process is one of the prepared codepages of the system (if present).

process_codepage_set($cp)

sets the currently active codepage. [Affects printer output, in/out codepages of sessions started by this process, and the default codepage for drawing in PM; is inherited by kids. Does not affect the out- and in-codepages of the session.]

ppid()

returns the PID of the parent process.

ppidOf($pid = $$)

returns the PID of the parent process of $pid. -1 on error.

sidOf($pid = $$)

returns the session id of the process id $pid. -1 on error.

Control of VIO sessions

VIO applications are applications running in a text-mode session.

out_codepage()

gets code page used for screen output (glyphs). -1 means that a user font was loaded.

out_codepage_set($cp)

sets code page used for screen output (glyphs). -1 switches to a preloaded user font. -2 switches off the preloaded user font.

in_codepage()

gets code page used for keyboard input. 0 means that a hardware codepage is used.

in_codepage_set($cp)

sets code page used for keyboard input.

($w, $h) = scrsize()

width and height of the given console window in character cells.

scrsize_set([$w, ] $h)

set height (and optionally width) of the given console window in character cells. Use 0 size to keep the old size.

($s, $e, $w, $a) = cursor()

gets start/end lines of the blinking cursor in the charcell, its width (1 on text modes) and attribute (-1 for hidden, in text modes other values mean visible, in graphic modes color).

cursor_set($s, $e, [$w [, $a]])

sets start/end lines of the blinking cursor in the charcell. Negative values mean percents of the character cell height.

screen()

gets a buffer with characters and attributes of the screen.

screen_set($buffer)

restores the screen given the result of screen(). E.g., if the file $file contains the screen contents, then

open IN, '<', $file or die;
binmode IN;
read IN, $in, -s IN;
$s = screen;
$in .= qq(\0) x (length($s) - length $in);
substr($in, length $s) = '';
screen_set $in;

will restore the screen content even if the height of the window changed (if the width changed, more manipulation is needed).

Control of the process list

With the exception of Title_set(), all these calls require that PM is running, they would not work under alternative Session Managers.

process_entry()

returns a list of the following data:

  • Title of the process (in the Ctrl-Esc list);

  • window handle of switch entry of the process (in the Ctrl-Esc list);

  • window handle of the icon of the process;

  • process handle of the owner of the entry in Ctrl-Esc list;

  • process id of the owner of the entry in Ctrl-Esc list;

  • session id of the owner of the entry in Ctrl-Esc list;

  • whether visible in Ctrl-Esc list;

  • whether item cannot be switched to (note that it is not actually grayed in the Ctrl-Esc list));

  • whether participates in jump sequence;

  • program type. Possible values are:

    PROG_DEFAULT                       0
    PROG_FULLSCREEN                    1
    PROG_WINDOWABLEVIO                 2
    PROG_PM                            3
    PROG_VDM                           4
    PROG_WINDOWEDVDM                   7

    Although there are several other program types for WIN-OS/2 programs, these do not show up in this field. Instead, the PROG_VDM or PROG_WINDOWEDVDM program types are used. For instance, for PROG_31_STDSEAMLESSVDM, PROG_WINDOWEDVDM is used. This is because all the WIN-OS/2 programs run in DOS sessions. For example, if a program is a windowed WIN-OS/2 program, it runs in a PROG_WINDOWEDVDM session. Likewise, if it's a full-screen WIN-OS/2 program, it runs in a PROG_VDM session.

  • switch-entry handle.

Optional arguments: the pid and the window-handle of the application running in the OS/2 session to query.

process_hentry()

similar to process_entry(), but returns a hash reference, the keys being

title owner_hwnd icon_hwnd owner_phandle owner_pid owner_sid
visible nonswitchable jumpable ptype sw_entry

(a copy of the list of keys is in @hentry_fields).

process_entries()

similar to process_entry(), but returns a list of array reference for all the elements in the switch list (one controlling Ctrl-Esc window).

process_hentries()

similar to process_hentry(), but returns a list of hash reference for all the elements in the switch list (one controlling Ctrl-Esc window).

change_entry()

changes a process entry, arguments are the same as process_entry() returns.

change_entryh()

Similar to change_entry(), but takes a hash reference as an argument.

process_hwnd()

returns the owner_hwnd of the process entry (for VIO windowed processes this is the frame window of the session).

Title()

returns the text of the task switch menu entry of the current session. (There is no way to get this info in non-standard Session Managers. This implementation is a shortcut via process_entry().)

Title_set(newtitle)

tries two different interfaces. The Session Manager one does not work with some windows (if the title is set from the start). This is a limitation of OS/2, in such a case $^E is set to 372 (type

help 372

for a funny - and wrong - explanation ;-). In such cases a direct-manipulation of low-level entries is used (same as bothTitle_set()). Keep in mind that some versions of OS/2 leak memory with such a manipulation.

winTitle()

returns text of the titlebar of the current process' window.

winTitle_set(newtitle)

sets text of the titlebar of the current process' window. The change does not affect the text of the switch entry of the current window.

swTitle_set(newtitle)

sets text of the task switch menu entry of the current process' window. [There is no API to query this title.] Does it via SwitchEntry interface, not Session manager interface. The change does not affect the text of the titlebar of the current window.

bothTitle_set(newtitle)

sets text of the titlebar and task switch menu of the current process' window via direct manipulation of the windows' texts.

SwitchToProgram([$sw_entry])

switch to session given by a switch list handle (defaults to the entry of our process).

Use of this function causes another window (and its related windows) of a PM session to appear on the front of the screen, or a switch to another session in the case of a non-PM program. In either case, the keyboard (and mouse for the non-PM case) input is directed to the new program.

Control of the PM windows

Some of these API's require sending a message to the specified window. In such a case the process needs to be a PM process, or to be morphed to a PM process via OS2::MorphPM().

For a temporary morphing to PM use the OS2::localMorphPM class.

Keep in mind that PM windows are engaged in 2 "orthogonal" window trees, as well as in the z-order list.

One tree is given by the parent/child relationship. This relationship affects drawing (child is drawn relative to its parent (lower-left corner), and the drawing is clipped by the parent's boundary; parent may request that it's drawing is clipped to be confined to the outsize of the child's and/or siblings' windows); hiding; minimizing/restoring; and destroying windows.

Another tree (not necessarily connected?) is given by ownership relationship. Ownership relationship assumes cooperation of the engaged windows via passing messages on "important events"; e.g., scrollbars send information messages when the "bar" is moved, menus send messages when an item is selected; frames move/hide/unhide/minimize/restore/change-z-order-of owned frames when the owner is moved/etc., and destroy the owned frames (even when these frames are not descendants) when the owner is destroyed; etc. [An important restriction on ownership is that owner should be created by the same thread as the owned thread, so they engage in the same message queue.]

Windows may be in many different state: Focused (take keyboard events) or not, Activated (=Frame windows in the parent/child tree between the root and the window with the focus; usually indicate such "active state" by titlebar highlights, and take mouse events) or not, Enabled/Disabled (this influences the ability to update the graphic, and may change appearance, as for enabled/disabled buttons), Visible/Hidden, Minimized/Maximized/Restored, Modal or not, etc.

The APIs below all die() on error with the message being $^E.

WindowText($hwnd)

gets "a text content" of a window. Requires (morphing to) PM.

WindowText_set($hwnd, $text)

sets "a text content" of a window. Requires (morphing to) PM.

($x, $y, $flags, $width, $height, $behind, @rest) = WindowPos($hwnd)

gets window position info as 8 integers (of SWP), in the order suitable for WindowPos_set(). @rest is marked as "reserved" in PM docs. $flags is a combination of SWP_* constants.

$hash = hWindowPos($hwnd)

gets window position info as a hash reference; the keys are flags width height x y behind hwnd reserved1 reserved2.

Example:

exit unless $hash->{flags} & SWP_MAXIMIZE;	# Maximized
WindowPos_set($hwnd, $x, $y, $flags = SWP_MOVE, $width = 0, $height = 0, $behind = HWND_TOP)

Set state of the window: position, size, zorder, show/hide, activation, minimize/maximize/restore etc. Which of these operations to perform is governed by $flags.

hWindowPos_set($hash, [$hwnd])

Same as WindowPos_set, but takes the position from keys fl width height x y behind hwnd of the hash referenced by $hash. If $hwnd is explicitly specified, it overrides $hash->{hwnd}. If $hash->{flags} is not specified, it is calculated basing on the existing keys of $hash. Requires (morphing to) PM.

Example:

hWindowPos_set {flags => SWP_MAXIMIZE}, $hwnd; # Maximize
($pid, $tid) = WindowProcess($hwnd)

gets PID and TID of the process associated to the window.

ClassName($hwnd)

returns the class name of the window.

If this window is of any of the preregistered WC_* classes the class name returned is in the form "#nnnnn", where "nnnnn" is a group of up to five digits that corresponds to the value of the WC_* class name constant.

WindowStyle($hwnd)

Returns the "window style" flags for window handle $hwnd.

WindowULong($hwnd, $id), WindowPtr($hwnd, $id), WindowUShort($hwnd, $id)

Return data associated to window handle $hwnd. $id should be one of QWL_*, QWP_PFNWP, QWS_* constants, or a byte offset referencing a region (of length 4, 4, 2 correspondingly) fully inside 0..cbWindowData-1. Here cbWindowData is the count of extra user-specified bytes reserved for the given class of windows.

WindowULong_set($hwnd, $id, $value), WindowPtr_set, WindowUShort_set

Similar to WindowULong(), WindowPtr(), WindowUShort(), but for assigning the value $value.

WindowBits_set($hwnd, $id, $value, $mask)

Similar to WindowULong_set(), but will change only the bits which are set in $mask.

FocusWindow()

returns the handle of the focus window. Optional argument for specifying the desktop to use.

FocusWindow_set($hwnd)

set the focus window by handle. Optional argument for specifying the desktop to use. E.g, the first entry in program_entries() is the Ctrl-Esc list. To show an application, use either one of

WinShowWindow( $hwnd, 1 );
FocusWindow_set( $hwnd );
SwitchToProgram($switch_handle);

(Which work with alternative focus-to-front policies?) Requires (morphing to) PM.

Switching focus to currently-unfocused window moves the window to the front in Z-order; use FocusWindow_set_keep_Zorder() to avoid this.

FocusWindow_set_keep_Zorder($hwnd)

same as FocusWindow_set(), but preserves the Z-order of windows.

ActiveWindow([$parentHwnd])

gets the active subwindow's handle for $parentHwnd or desktop. Returns FALSE if none.

ActiveWindow_set($hwnd, [$parentHwnd])

sets the active subwindow's handle for $parentHwnd or desktop. Requires (morphing to) PM.

ShowWindow($hwnd [, $show])

Set visible/hidden flag of the window. Default: $show is TRUE.

EnableWindowUpdate($hwnd [, $update])

Set window visibility state flag for the window for subsequent drawing. No actual drawing is done at this moment. Use ShowWindow($hwnd, $state) when redrawing is needed. While update is disabled, changes to the "window state" do not change the appearance of the window. Default: $update is TRUE.

(What is manipulated is the bit WS_VISIBLE of the window style.)

EnableWindow($hwnd [, $enable])

Set the window enabled state. Default: $enable is TRUE.

Results in WM_ENABLED message sent to the window. Typically, this would change the appearance of the window. If at the moment of disabling focus is in the window (or a descendant), focus is lost (no focus anywhere). If focus is needed, it can be reassigned explicitly later.

IsWindowEnabled(), IsWindowVisible(), IsWindowShowing()

these functions take $hwnd as an argument. IsWindowEnabled() queries the state changed by EnableWindow(), IsWindowVisible() the state changed by ShowWindow(), IsWindowShowing() is true if there is a part of the window visible on the screen.

PostMsg($hwnd, $msg, $mp1, $mp2)

post message to a window. The meaning of $mp1, $mp2 is specific for each message id $msg, they default to 0. E.g.,

  use OS2::Process qw(:DEFAULT WM_SYSCOMMAND WM_CONTEXTMENU
		      WM_SAVEAPPLICATION WM_QUIT WM_CLOSE
		      SC_MAXIMIZE SC_RESTORE);
  $hwnd = process_hentry()->{owner_hwnd};
  # Emulate choosing `Restore' from the window menu:
  PostMsg $hwnd, WM_SYSCOMMAND, MPFROMSHORT(SC_RESTORE); # Not
                                                         # immediate

  # Emulate `Show-Contextmenu' (Double-Click-2), two ways:
  PostMsg ActiveWindow, WM_CONTEXTMENU;
  PostMsg FocusWindow, WM_CONTEXTMENU;

  /* Emulate `Close' */
  PostMsg ActiveWindow, WM_CLOSE;

  /* Same but with some "warnings" to the application */
  $hwnd = ActiveWindow;
  PostMsg $hwnd, WM_SAVEAPPLICATION;
  PostMsg $hwnd, WM_CLOSE;
  PostMsg $hwnd, WM_QUIT;

In fact, MPFROMSHORT() may be omitted above.

For messages to other processes, messages which take/return a pointer are not supported.

MP*()

The functions MPFROMSHORT(), MPVOID(), MPFROMCHAR(), MPFROM2SHORT(), MPFROMSH2CH(), MPFROMLONG() can be used the same way as from C. Use them to construct parameters $m1, $m2 to PostMsg().

These functions are not exported by default.

$eh = BeginEnumWindows($hwnd)

starts enumerating immediate child windows of $hwnd in z-order. The enumeration reflects the state at the moment of BeginEnumWindows() calls; use IsWindow() to be sure. All the functions in this group require (morphing to) PM.

$kid_hwnd = GetNextWindow($eh)

gets the next kid in the list. Gets 0 on error or when the list ends.

EndEnumWindows($eh)

End enumeration and release the list.

@list = ChildWindows([$hwnd])

returns the list of child windows at the moment of the call. Same remark as for enumeration interface applies. Defaults to HWND_DESKTOP. Example of usage:

sub l {
  my ($o,$h) = @_;
  printf ' ' x $o . "%#x\n", $h;
  l($o+2,$_) for ChildWindows $h;
}
l 0, $HWND_DESKTOP
IsWindow($hwnd)

true if the window handle is still valid.

QueryWindow($hwnd, $type)

gets the handle of a related window. $type should be one of QW_* constants.

IsChild($hwnd, $parent)

return TRUE if $hwnd is a descendant of $parent.

WindowFromId($hwnd, $id)

return a window handle of a child of $hwnd with the given $id.

hwndSysMenu = WinWindowFromID(hwndDlg, FID_SYSMENU);
WinSendMsg(hwndSysMenu, MM_SETITEMATTR,
    MPFROM2SHORT(SC_CLOSE, TRUE),
    MPFROM2SHORT(MIA_DISABLED, MIA_DISABLED));
WindowFromPoint($x, $y [, $hwndParent [, $descedantsToo]])

gets a handle of a child of $hwndParent at ($x,$y). If $descedantsToo (defaulting to 1) then children of children may be returned too. May return $hwndParent (defaults to desktop) if no suitable children are found, or 0 if the point is outside the parent.

$x and $y are relative to $hwndParent.

EnumDlgItem($dlgHwnd, $type [, $relativeHwnd])

gets a dialog item window handle for an item of type $type of $dlgHwnd relative to $relativeHwnd, which is descendant of $dlgHwnd. $relativeHwnd may be specified if $type is EDI_FIRSTTABITEM or EDI_LASTTABITEM.

The return is always an immediate child of hwndDlg, even if hwnd is not an immediate child window. $type may be

EDI_FIRSTGROUPITEM

First item in the same group.

EDI_FIRSTTABITEM

First item in dialog with style WS_TABSTOP. hwnd is ignored.

EDI_LASTGROUPITEM

Last item in the same group.

EDI_LASTTABITEM

Last item in dialog with style WS_TABSTOP. hwnd is ignored.

EDI_NEXTGROUPITEM

Next item in the same group. Wraps around to beginning of group when the end of the group is reached.

EDI_NEXTTABITEM

Next item with style WS_TABSTOP. Wraps around to beginning of dialog item list when end is reached.

EDI_PREVGROUPITEM

Previous item in the same group. Wraps around to end of group when the start of the group is reached. For information on the WS_GROUP style, see Window Styles.

EDI_PREVTABITEM

Previous item with style WS_TABSTOP. Wraps around to end of dialog item list when beginning is reached.

DesktopWindow()

gets the actual window handle of the PM desktop; most APIs accept the pseudo-handle HWND_DESKTOP instead. Keep in mind that the WPS desktop (one with WindowText() being "Desktop") is a different beast?!

TopLevel($hwnd)

gets the toplevel window of $hwnd.

ResetWinError()

Resets $^E. One may need to call it before the Win*-class APIs which may return 0 during normal operation. In such a case one should check both for return value being zero and $^E being non-zero. The following APIs do ResetWinError() themselves, thus do not need an explicit one:

WindowPtr
WindowULong
WindowUShort
WindowTextLength
ActiveWindow
PostMsg

This function is normally not needed. Not exported by default.

Control of the PM data

ActiveDesktopPathname()

gets the path of the directory which corresponds to Desktop.

InvalidateRect
CreateFrameControls

Control of the PM clipboard

ClipbrdText()

gets the content of the clipboard. An optional argument is the format of the data in the clipboard (defaults to CF_TEXT). May croak with error PMERR_INVALID_HWND if no data of given $fmt is present.

Note that the usual convention is to have clipboard data with "\r\n" as line separators. This function will only work with clipboard data types which are delimited by "\0" byte (not included in the result).

ClipbrdText_2byte

Same as ClipbrdText(), but will only work with clipboard data types which are collection of C shorts delimited by 0 short (not included in the result).

ClipbrdTextUCS2le

Same as ClipbrdText_2byte(), but will assume that the shorts represent an Unicode string in UCS-2le format (little-endian 2-byte representation of Unicode), and will provide the result in Perl internal utf8 format (one short of input represents one Perl character).

Note that Firefox etc. export their selection in unicode types of this format.

ClipbrdText_set($txt, [$no_convert_nl, [$fmt, [$fmtinfo, [$hab] ] ] ] )

sets the text content of the clipboard after removing old contents. Unless the optional argument $no_convert_nl is TRUE, will convert newlines to "\r\n". Another optional argument $fmt is the format of the data in the clipboard (should be an atom, defaults to CF_TEXT). Other arguments are as for ClipbrdData_set. Croaks on failure.

ClipbrdFmtInfo( [$fmt, [ $hab ] ])

returns the $fmtInfo flags set by the application which filled the format $fmt of the clipboard. $fmt defaults to CF_TEXT.

ClipbrdOwner( [ $hab ] )

Returns window handle of the current clipboard owner.

ClipbrdViewer( [ $hab ] )

Returns window handle of the current clipboard viewer.

ClipbrdData( [$fmt, [ $hab ] ])

Returns a handle to clipboard data of the given format as an integer. Format defaults to CF_TEXT (in this case the handle is a memory address).

Clipboard should be opened before calling this function. May croak with error PMERR_INVALID_HWND if no data of given $fmt is present.

The result should not be used after clipboard is closed. Hence a return handle of type CLI_POINTER may need to be converted to a string and stored for future usage. Use MemoryRegionSize() to get a high estimate on the length of region addressed by this pointer; the actual length inside this region should be obtained by knowing particular format of data. E.g., it may be 0-byte terminated for string types, or 0-short terminated for wide-char string types.

OpenClipbrd( [ $hab ] )

claim read access to the clipboard. May need a message queue to operate. May block until other processes finish dealing with clipboard.

CloseClipbrd( [ $hab ] )

Allow other processes access to clipboard. Clipboard should be opened before calling this function.

ClipbrdData_set($data, [$convert_nl, [$fmt, [$fmtInfo, [ $hab] ] ] ] )

Sets the clipboard data of format given by atom $fmt. Format defaults to CF_TEXT.

$fmtInfo should declare what type of handle $data is; it should be either CFI_POINTER, or CFI_HANDLE (possibly qualified by CFI_OWNERFREE and CFI_OWNERDRAW flags). It defaults to CFI_HANDLE for $fmt being standard bitmap, metafile, and palette (undocumented???) formats; otherwise defaults to CFI_POINTER. If format is CFI_POINTER, $data should contain the string to copy to clipboard; otherwise it should be an integer handle.

If $convert_nl is TRUE (the default), "\n" in $data are converted to "\r\n" pairs if $fmt is CFI_POINTER (as is the convention for text format of the clipboard) unless they are already in such a pair.

_ClipbrdData_set($data, [$fmt, [$fmtInfo, [ $hab] ] ] )

Sets the clipboard data of format given by atom $fmt. Format defaults to CF_TEXT. $data should be an address (in givable unnamed shared memory which should not be accessed or manipulated after this call) or a handle in a form of an integer.

$fmtInfo has the same semantic as for ClipbrdData_set().

ClipbrdOwner_set( $hwnd, [ $hab ] )

Sets window handle of the current clipboard owner (window which gets messages when content of clipboard is retrieved).

ClipbrdViewer_set( $hwnd, [ $hab ] )

Sets window handle of the current clipboard owner (window which gets messages when content of clipboard is changed).

ClipbrdFmtNames()

Returns list of names of formats currently available in the clipboard.

ClipbrdFmtAtoms()

Returns list of atoms of formats currently available in the clipboard.

EnumClipbrdFmts($fmt [, $hab])

Low-level access to the list of formats currently available in the clipboard. Returns the atom for the format of clipboard after $fmt. If $fmt is 0, returns the first format of clipboard. Returns 0 if $fmt is the last format. Example:

{
  my $h = OS2::localClipbrd->new('nomorph');
  my $fmt = 0;
  push @formats, AtomName $fmt
    while $fmt = EnumClipbrdFmts $fmt;
}

Clipboard should be opened before calling this function. May croak if no format is present.

EmptyClipbrd( [ $hab ] )

Remove all the data handles in the clipboard. croak()s on failure. Clipboard should be opened before calling this function.

Recommended before assigning a value to clipboard to remove extraneous formats of data from clipboard.

($size, $flags) = MemoryRegionSize($addr, [$size_lim, [ $interrupt ]])

$addr should be a memory address (encoded as integer). This call finds the largest continuous region of memory belonging to the same memory object as $addr, and having the same memory flags as $addr. $flags is the value of the memory flag of $addr (see docs of DosQueryMem(3) for details). If optional argument $size_lim is given, the search is restricted to the region this many bytes long (after $addr).

($addr and $size are rounded so that all the memory pages containing the region are inspected.) Optional argument $interrupt (defaults to 1) specifies whether region scan should be interruptible by signals.

Use class OS2::localClipbrd to ensure that clipboard is closed even if the code in the block made a non-local exit.

See the "OS2::localMorphPM, OS2::localFlashWindow, and OS2::localClipbrd classes"

Control of the PM atom tables

Low-level methods to access the atom table(s). $atomtable defaults to the SystemAtomTable().

AddAtom($name, [$atomtable])

Returns the atom; increments the use count unless $name is a name of an integer atom.

FindAtom($name, [$atomtable])

Returns the atom if it exists, 0 otherwise (actually, croaks).

DeleteAtom($name, [$atomtable])

Decrements the use count unless $name is a name of an integer atom. When count goes to 0, association of the name to an integer is removed. (Version with prepended underscore returns 0 on success.)

AtomName($atom, [$atomtable])

Returns the name of the atom. Integer atoms have names of format "#ddddd" of variable length up to 7 chars.

AtomLength($atom, [$atomtable])

Returns the length of the name of the atom. Return of 0 means that no such atom exists (but usually croaks in such a case).

Integer atoms always return length 6.

AtomUsage($name, [$atomtable])

Returns the usage count of the atom.

SystemAtomTable()

Returns central atom table accessible to any process.

CreateAtomTable( [ $initial, [ $buckets ] ] )

Returns new per-process atom table. See docs for WinCreateAtomTable(3).

DestroyAtomTable($atomtable)

Dispose of the table. (Version with prepended underscore returns 0 on success.)

Alerting the user

Alarm([$type])

Audible alarm of type $type (defaults to WA_ERROR=2). Other useful values are WA_WARNING=0, WA_NOTE=1. (What is WA_CDEFALARMS=3???)

The duration and frequency of the alarms can be changed by the OS2::SysValues_set(). The alarm frequency is defined to be in the range 0x0025 through 0x7FFF. The alarm is not generated if system value SV_ALARM is set to FALSE. The alarms are dependent on the device capability.

FlashWindow($hwnd, $doFlash)

Starts/stops (depending on $doFlash being TRUE/FALSE) flashing the window $hwnd's borders and titlebar. First 5 flashes are accompanied by alarm beeps.

Example (for VIO applications):

{ my $morph = OS2::localMorphPM->new(0);
  print STDERR "Press ENTER!\n";
  FlashWindow(process_hwnd, 1);
  <>;
  FlashWindow(process_hwnd, 0);
}

Since flashing window persists even when application ends, it is very important to protect the switching off flashing from non-local exits. Use the class OS2::localFlashWindow for this. Creating the object of this class starts flashing the window until the object is destroyed. The above example becomes:

print STDERR "Press ENTER!\n";
{ my $flash = OS2::localFlashWindow->new( process_hwnd );
  <>;
}

Notes from IBM docs: Flashing a window brings the user's attention to a window that is not the active window, where some important message or dialog must be seen by the user.

Note: It should be used only for important messages, for example, where some component of the system is failing and requires immediate attention to avoid damage.

MessageBox($text, [ $title, [$flags, ...] ])

Shows a simple messagebox with (optional) icon, message $text, and one or more buttons to dismiss the box. Returns the indicator of which action was taken by the user. If optional argument $title is not given, the title is constructed from the application name. The optional argument $flags describes the appearance of the box; the default is to have Cancel button, INFO-style icon, and a border for moving. Flags should be a combination of

Buttons on the box: or Button Group
    MB_OK                 OK
    MB_OKCANCEL           both OK and CANCEL
    MB_CANCEL             CANCEL
    MB_ENTER              ENTER
    MB_ENTERCANCEL        both ENTER and CANCEL
    MB_RETRYCANCEL        both RETRY and CANCEL
    MB_ABORTRETRYIGNORE   ABORT, RETRY, and IGNORE
    MB_YESNO              both YES and NO
    MB_YESNOCANCEL        YES, NO, and CANCEL

Color or Icon 
    MB_ICONHAND           a small red circle with a red line across
                          it.
    MB_ERROR              a small red circle with a red line across
                          it.
    MB_ICONASTERISK       an information (i) icon. 
    MB_INFORMATION        an information (i) icon. 
    MB_ICONEXCLAMATION    an exclamation point (!) icon. 
    MB_WARNING            an exclamation point (!) icon. 
    MB_ICONQUESTION       a question mark (?) icon. 
    MB_QUERY              a question mark (?) icon. 
    MB_NOICON             No icon.

Default action (i.e., focussed button; default is MB_DEFBUTTON1)
    MB_DEFBUTTON1         The first button is the default
                          selection.
    MB_DEFBUTTON2         The second button is the default
                          selection.
    MB_DEFBUTTON3         The third button is the default
                          selection.

Modality indicator 
    MB_APPLMODAL                  Message box is application modal
                                  (default).
    MB_SYSTEMMODAL                Message box is system modal. 

Mobility indicator 
    MB_MOVEABLE                   Message box is moveable. 

With MB_MOVEABLE the message box is displayed with a title bar and a system menu, which shows only the Move, Close, and Task Manager choices, which can be selected either by use of the pointing device or by accelerator keys. If the user selects Close, the message box is removed and the usResponse is set to MBID_CANCEL, whether or not a cancel button existed within the message box.

Esc key dismisses the dialogue only if CANCEL button is present; the return value is MBID_CANCEL.

With MB_APPLMODAL the owner of the dialogue is disabled; therefore, do not specify the owner as the parent if this option is used.

Additionally, the following flag is possible, but probably not very useful:

Help button
    MB_HELP            a HELP button appears, which sends a WM_HELP
                       message is sent to the window procedure of
                       the message box.

Other optional arguments: $parent window, $owner_window, $helpID (used with WM_HELP message if MB_HELP style is given).

The return value is one of

MBID_ENTER           ENTER was selected 
MBID_OK              OK was selected 
MBID_CANCEL          CANCEL was selected 
MBID_ABORT           ABORT was selected 
MBID_RETRY           RETRY was selected 
MBID_IGNORE          IGNORE was selected 
MBID_YES             YES was selected 
MBID_NO              NO was selected 

0                    Function not successful; an error occurred.

BUGS??? keyboard transversal by pressing TAB key does not work. Do not appear in window list, so may be hard to find if covered by other windows.

_MessageBox($text, [ $title, [$flags, ...] ])

Similar to MessageBox(), but the default $title does not depend on the name of the script.

MessageBox2($text, [ $buttons_Icon, [$title, ...] ])

Similar to MessageBox(), but allows more flexible choice of button texts and the icon. $buttons_Icon is a reference to an array with information about buttons and the icon to use; the semantic of this array is the same as for argument list of process_MB2_INFO(). The default value will show one button Dismiss which will return 0x1000.

Other optional arguments are the same as for MessageBox().

NOTE. Remark about MBID_CANCEL in presence of MB_MOVABLE is equally applicable to MessageBox() and MessageBox2().

Example:

print MessageBox2
  'Foo prints 100, Bar 101, Baz 102',
  [['~Foo' => 100, 'B~ar' => 101, ['Ba~z'] => 102]],
  'Choose a number to print';

will show a messagebox with

Title

Choose a number to print,

Text

Foo prints 100, Bar 101, Baz 102

Icon

INFORMATION ICON

Buttons

Foo, Bar, Baz

Default button

Baz

accelerator keys

F, a, and z

return values

100, 101, and 102 correspondingly,

Using

print MessageBox2
  'Foo prints 100, Bar 101, Baz 102',
  [['~Foo' => 100, 'B~ar' => 101, ['Ba~z'] => 102], 'SP#22'],
  'Choose a number to print';

will show the 22nd system icon as the dialog icon (small folder icon).

_MessageBox2($text, $buttons_Icon_struct, [$title, ...])

low-level workhorse to implement MessageBox2(). Differs by the default $title, and that $buttons_Icon_struct is required, and is a string with low-level C struct.

process_MB2_INFO($buttons, [$iconID, [$flags, [$notifyWindow]]])

low-level workhorse to implement MessageBox2(); calculates the second argument of _MessageBox2(). $buttons is a reference to array of button descriptions. $iconID is either an ID of icon for the message box, or a string of the form "SP#number"; in the latter case the number's system icon is chosen; this field is ignored unless $flags contains MB_CUSTOMICON flag. $flags has the same meaning as mobility, modality, and icon flags for MessageBox() with addition of extra flags

MB_CUSTOMICON         Use a custom icon specified in hIcon. 
MB_NONMODAL           Message box is nonmodal

$flags defaults to MB_INFORMATION or MB_CUSTOMICON (depending on whether $iconID is non-0), combined with MB_MOVABLE.

Each button's description takes two elements of the description array, appearance description, and the return value of MessageBox2() if this button is selected. The appearance description is either an array reference of the form [$button_Text, $button_Style], or the same without $button_Style (then style is BS_DEFAULT, making this button the default) or just $button_Text (with "normal" style). E.g., the list

Foo => 100, Bar => 101, [Baz] => 102

will show three buttons Foo, Bar, Baz with Baz being the default button; pressing buttons return 100, 101, or 102 correspondingly.

In particular, exactly one button should have BS_DEFAULT style (e.g., given as [$button_Name]); otherwise the message box will not have keyboard focus! (The only exception is the case of one button; then [$button_Name] can be replaced (for convenience) with plain $button_Name.)

If text of the button contains character ~, the following character becomes the keyboard accelerator for this button. One can also get the handle of system icons directly, so 'SP#22' can be replaced by OS2::Process::get_pointer(22); see also SPTR_* constants.

NOTE With MB_NONMODAL the program continues after displaying the nonmodal message box. The message box remains visible until the owner window destroys it. Two notification messages, WM_MSGBOXINIT and WM_MSGBOXDISMISS, are used to support this non-modality.

LoadPointer($id, [$module, [$hwnd]])

Loads a handle for the pointer $id from the resources of the module $module on desktop $hwnd. If $module is 0 (default), loads from the main executable; otherwise from a DLL with the handle $module.

The pointer is owned by the process, and is destroyed by DestroyPointer() call, or when the process terminates.

SysPointer($id, [$copy, [$hwnd]])

Gets a handle for (a copy of) the system pointer $id (the value should be one of SPTR_* constants). A copy is made if $copy is TRUE (the default). $hwnd defaults to HWND_DESKTOP.

get_pointer($id, [$copy, [$hwnd]])

Gets (and caches) a copy of the system pointer.

Constants used by OS/2 APIs

Function os2constant($name) returns the value of the constant; to decrease the memory usage of this package, only the constants used by APIs called by Perl functions in this package are made available.

For direct access, see also the "EXPORTS" section; the latter way may also provide some performance advantages, since the value of the constant is cached.

OS2::localMorphPM, OS2::localFlashWindow, and OS2::localClipbrd classes

The class OS2::localMorphPM morphs the process to PM for the duration of the given scope.

{
  my $h = OS2::localMorphPM->new(0);
  # Do something
}

The argument has the same meaning as one to OS2::MorphPM(). Calls can nest with internal ones being NOPs.

Likewise, OS2::localClipbrd class opens the clipboard for the duration of the current scope; if TRUE optional argument is given, it would not morph the application into PM:

{
  my $handle = OS2::localClipbrd->new(1);	# Do not morph into PM
  # Do something with clipboard here...
}

OS2::localFlashWindow behaves similarly; see "FlashWindow($hwnd, $doFlash)".

EXAMPLES

The test suite for this module contains an almost comprehensive collection of examples of using the API of this module.

TODO

Add tests for:

	SwitchToProgram
	ClassName
	out_codepage
	out_codepage_set
	in_codepage
	in_codepage_set
	cursor
	cursor_set
	screen
	screen_set
	process_codepages
	QueryWindow
	EnumDlgItem
        WindowPtr
        WindowUShort
        SetWindowBits
        SetWindowPtr
        SetWindowULong
        SetWindowUShort
	my_type
	file_type
	scrsize
	scrsize_set

Document: InvalidateRect, CreateFrameControls, kbdChar, kbdhChar, kbdStatus, _kbdStatus_set, kbdhStatus, kbdhStatus_set, vioConfig, viohConfig, vioMode, viohMode, viohMode_set, _vioMode_set, _vioState, _vioState_set, vioFont, vioFont_set

Test: SetWindowULong/Short/Ptr, SetWindowBits. InvalidateRect, CreateFrameControls, ClipbrdOwner_set, ClipbrdViewer_set, _ClipbrdData_set, Alarm, FlashWindow, _MessageBox, MessageBox, _MessageBox2, MessageBox2, LoadPointer, SysPointer, kbdChar, kbdhChar, kbdStatus, _kbdStatus_set, kbdhStatus, kbdhStatus_set, vioConfig, viohConfig, vioMode, viohMode, viohMode_set, _vioMode_set, _vioState, _vioState_set, vioFont, vioFont_set

Implement SOMETHINGFROMMR.

 >But I wish to change the default button if the user enters some
 >text into an entryfield.  I can detect the entry ok, but can't
 >seem to get the button to change to default.
 >
 >No matter what message I send it, it's being ignored.

 You need to get the style of the buttons using
 WinQueryWindowULong/QWL_STYLE, set and reset the BS_DEFAULT bits as
 appropriate and then use WinSetWindowULong/QWL_STYLE to set the
 button style.  Something like this:
   hwnd1 = WinWindowFromID (hwnd, id1);
   hwnd2 = WinWindowFromID (hwnd, id2);
   style1 = WinQueryWindowULong (hwnd1, QWL_STYLE);
   style2 = WinQueryWindowULong (hwnd2, QWL_STYLE);
   style1 |= style2 & BS_DEFAULT;
   style2 &= ~BS_DEFAULT;
   WinSetWindowULong (hwnd1, QWL_STYLE, style1);
   WinSetWindowULong (hwnd2, QWL_STYLE, style2);

> How to do query and change a frame creation flags for existing
> window?

Set the style bits that correspond to the FCF_* flag for the frame
window and then send a WM_UPDATEFRAME message with the appropriate
FCF_* flag in mp1.

ULONG ulFrameStyle;
ulFrameStyle = WinQueryWindowULong( WinQueryWindow(hwnd, QW_PARENT),
QWL_STYLE );
ulFrameStyle = (ulFrameStyle & ~FS_SIZEBORDER) | FS_BORDER;
WinSetWindowULong(   WinQueryWindow(hwnd, QW_PARENT),
                     QWL_STYLE,
                     ulFrameStyle );
WinSendMsg( WinQueryWindow(hwnd, QW_PARENT),
            WM_UPDATEFRAME,
            MPFROMP(FCF_SIZEBORDER),
            MPVOID );

If the FCF_* flags you want to change does not have a corresponding
FS_* style (i.e. the FCF_* flag corresponds to the presence/lack of a
frame control rather than a property of the frame itself) then you
create or destroy the appropriate control window using the correct
FID_* window identifier and then send the WM_UPDATEFRAME message with
the appropriate FCF_* flag in mp1.

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
 |  SetFrameBorder()                                                 |
 |    Changes a frame window's border to the requested type.         |
 |                                                                   |
 |  Parameters on entry:                                             |
 |    hwndFrame     -> Frame window whose border is to be changed.   |
 |    ulBorderStyle -> Type of border to change to.                  |
 |                                                                   |
 |  Returns:                                                         |
 |    BOOL          -> Success indicator.                            |
 |                                                                   |
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
BOOL SetFrameBorder( HWND hwndFrame, ULONG ulBorderType )  {
  ULONG  ulFrameStyle;
  BOOL   fSuccess = TRUE;

  ulFrameStyle = WinQueryWindowULong( hwndFrame, QWL_STYLE );

  switch ( ulBorderType )  {
    case FS_SIZEBORDER :
      ulFrameStyle = (ulFrameStyle & ~(FS_DLGBORDER | FS_BORDER))
                     | FS_SIZEBORDER;
      break;

    case FS_DLGBORDER :
      ulFrameStyle = (ulFrameStyle & ~(FS_SIZEBORDER | FS_BORDER))
                     | FS_DLGBORDER;
      break;

    case FS_BORDER :
      ulFrameStyle = (ulFrameStyle & ~(FS_SIZEBORDER | FS_DLGBORDER))
                     | FS_BORDER;
      break;

    default :
      fSuccess = FALSE;
      break;
  }  // end switch

  if ( fSuccess )  {
    fSuccess = WinSetWindowULong( hwndFrame, QWL_STYLE, ulFrameStyle );

    if ( fSuccess )  {
      fSuccess = (BOOL)WinSendMsg( hwndFrame, WM_UPDATEFRAME, 0, 0 );
      if ( fSuccess )
        fSuccess = WinInvalidateRect( hwndFrame, NULL, TRUE );
    }
  }

  return ( fSuccess );

}  // End SetFrameBorder()

        hwndMenu=WinLoadMenu(hwndParent,NULL,WND_IMAGE);
        WinSetWindowUShort(hwndMenu,QWS_ID,FID_MENU);
        ulStyle=WinQueryWindowULong(hwndMenu,QWL_STYLE);
        WinSetWindowULong(hwndMenu,QWL_STYLE,ulStyle|MS_ACTIONBAR);
        WinSendMsg(hwndParent,WM_UPDATEFRAME,MPFROMSHORT(FCF_MENU),0L);

 OS/2-windows have another "parent" called the *owner*,
 which must be set separately - to get a close relationship:

   WinSetOwner (hwndFrameChild, hwndFrameMain);

 Now your child should move with your main window!
 And always stays on top of it....

 To avoid this, for example for dialogwindows, you can
 also "disconnect" this relationship with:

   WinSetWindowBits (hwndFrameChild, QWL_STYLE
                     , FS_NOMOVEWITHOWNER
                     , FS_NOMOVEWITHOWNER);

Adding a button icon later:

/* switch the button style to BS_MINIICON */
WinSetWindowBits(hwndBtn, QWL_STYLE, BS_MINIICON, BS_MINIICON) ;

/* set up button control data */
BTNCDATA    bcd;
bcd.cb = sizeof(BTNCDATA);
bcd.hImage = WinLoadPointer(HWND_DESKTOP, dllHandle, ID_ICON_BUTTON1) ;
bcd.fsCheckState = bcd.fsHiliteState = 0 ;


WNDPARAMS   wp;
wp.fsStatus = WPM_CTLDATA;
wp.pCtlData = &bcd;

/* add the icon on the button */
WinSendMsg(hwndBtn, WM_SETWINDOWPARAMS, (MPARAM)&wp, NULL);

MO> Can anyone tell what OS/2 expects of an application to be properly
MO> minimized to the desktop?
case WM MINMAXFRAME :
{
  BOOL  fShow = ! (((PSWP) mp1)->fl & SWP MINIMIZE);
  HENUM henum;

  HWND  hwndChild;

  WinEnableWindowUpdate ( hwnd, FALSE );

  for (henum=WinBeginEnumWindows(hwnd);
       (hwndChild = WinGetNextWindow (henum)) != 0; )
  WinShowWindow ( hwndChild, fShow );

  WinEndEnumWindows ( henum );
  WinEnableWindowUpdate ( hwnd, TRUE );
}
break;

Why hWindowPos DesktopWindow gives behind => HWND_TOP?

$^E

the majority of the APIs of this module set $^E on failure (no matter whether they die() on failure or not). By the semantic of PM API which returns something other than a boolean, it is impossible to distinguish failure from a "normal" 0-return. In such cases $^E == 0 indicates an absence of error.

EXPORTS

In addition to symbols described above, the following constants (available also via module OS2::Process::Const) are exportable. Note that these symbols live in package OS2::Process::Const, they are not available by full name through OS2::Process!

HWND_*		Standard (abstract) window handles
WM_*			Message ids
SC_*			WM_SYSCOMMAND flavor
SWP_*			Size/move etc flag
WC_*			Standard window classes
PROG_*		Program category (PM, VIO etc)
QW_*			Query-Window flag
EDI_*			Enumerate-Dialog-Item code
WS_*			Window Style flag
QWS_*			Query-window-UShort offsets
QWP_*			Query-window-pointer offsets
QWL_*			Query-window-ULong offsets
FF_*			Frame-window state flags
FI_*			Frame-window information flags
LS_*			List box styles
FS_*			Frame style
FCF_*			Frame creation flags
BS_*			Button style
MS_*			Menu style
TBM_*			Title bar messages?
CF_*			Clipboard formats
CFI_*			Clipboard storage type
FID_*			ids of subwindows of frames

BUGS

whether a given API dies or returns FALSE/empty-list on error may be confusing. This may change in the future.

AUTHOR

Andreas Kaiser <ak@ananke.s.bawue.de>, Ilya Zakharevich <ilya@math.ohio-state.edu>.

SEE ALSO

spawn*() system calls, OS2::Proc and OS2::WinObject modules.