MENUS/PROMPTS

Name

MENUS/PROMPTS -- 

Function

nPosition           ACHOICE(<nTop>, <nLeft>, <nBottom>, <nRight>, <acMenuItems>, [<alSelectableItems> | <lSelectableItems>], [<cUserFunction>], [<nInitialItem>], [<nWindowRow>])
nChoice             ALERT( <cMessage>, [<aOptions>] )
nOption             FT_Ach2tb( <nToprow>,<nTopcol>[,<nBotrow>][,<nBotcol>],<aArrey>,     ; [<cBoxtype>],[<cBoxcolor>],[<cBoxtitle>],[<nTitlePos>],        ; [<cUselcolor>],[<cTitlecolor>],[<cBarcolor>],[<cHkcolor>],     ; [<lShadow>],[<lExecute>],[<nMsgrow>],[<nMsgcol>],              ; [<cMsg.color>],[cElevbar],[cEbarcolor],[<cEbarside>],          ; [<cNoSelcolor>],[<cTagch>],[<nStartelem>],[<lRscreen>],        ; [<nTimeout>],[<nTimeoutval>],[<cUserfunc>] )
                    FT_Adder()
NIL                 FT_BLINK( <cMsg>, [ <nRow> ], [ <nCol> ] )
nRecno              FT_BRWSWHL( <aFields>, <bWhileCond>, <cKey>,                  ; [ <nFreeze> ], [ <lSaveScrn> ], [ <cColorList> ], ; [ <cColorShadow> ], [ <nTop> ], [ <nLeft> ],      ; [ <nBottom> ], [ <nRight> ]
aClrData            FT_ClrSel( <aClrData>, [ <lClrMode> ], [ <cTestChr> ]
lKeyMatch           FT_DISPMSG( <aMessageArray>, [ <cKey2Check> ], [ <nTopBoxRow> ], [ <nLeftBoxColumn> ], [ <cnBoxType> ], [ <lShadow> ] )
NIL                 FT_FILL( <aSubArrayName>, <cMenuSelection>, <bFunction>, <lSelectable> )
NIL                 FT_MENU1( <acBarNames>, <acOptions>, <acAction>, <acColors> [, <nTopRow> ], [ <lShadow> ] )
NIL                 FT_MENU2( <aMenuarray> [, <cColors> ] )
                    #include "FTMENUTO.CH"  MENU TO <var> [COLD]
NIL                 FT_PENDING ( <cMsg>, [ <nRow> ], [ <nCol> ], ; [ <nWait> ], [ <cColor> ] )
cDayOfWeek          FT_PICKDAY()
                    #include "FTMENUTO.CH"  @ <nRow>, <nCol> PROMPT <cPrompt>                     ; [COLOR <cColor>]                     ; [MESSAGE <cMessage>]                 ; [MSGROW <nMsgRow>]                   ; [MSGCOL <nMsgCol>]                   ; [MSGCOLOR <cMsgColor>]               ; [TRIGGER <nTrigger>]                 ; [TRIGGERCOLOR <cTriggerColor>]       ; [HOME <nHome>]                       ; [END <nEnd>]                         ; [UP <nUp>]                           ; [DOWN <nDown>]                       ; [LEFT <nLeft>]                       ; [RIGHT <nRight>]                     ; [EXECUTE <bExec>]                    ;
nil                 FT_SLEEP( <nSeconds>, [<nInitial>] )
NIL                 FT_XBOX( [ <cJustType> ], [ <cRetWait> ], [ <cBorType> ],   ; [ <cBorColor> ], [ <cBoxColor> ], [ <nStartRow> ], ; [ <nStartCol> ], <cLine1>,  <cLine2>, <cLine3>,    ; <cLine4>, <cLine5>, <cLine6>, <cLine7>, <cLine8> )

Description

Function ACHOICE()

 ACHOICE(<верхняя строка>, <левая колонка>,
 <нижняя строка>, <правая колонка>,
 <массив меню>,
 [<массив логических значений>|<массив выбранных значений>],
 [<функция пользователя>],
 [<позиция маркера>],
 [<строка окна>]) --> номер элемента меню

ACHOICE() - функция, обеспечивающая интерфейс с пользователем, которую можно использовать для создания различных видов всплывающих (pop-up) меню. Каждое меню использует массив символьных строк в качестве элементов меню и параллельный массив логических значений, чтобы определять, доступны элементы для выбора или нет. При вызове ACHOICE() элементы меню высвечивается внутри окна с заданными координатами. Когда пользователь нажимает клавишу <Return>, выбирается текущий элемент, и ACHOICE() возвращает номер выбранного элемента в массиве <массив меню>. Когда пользователь нажимает клавишу <Esc>, выполнение ACHOICE() прерывается и она возвращает нуль.

Если количество элементов в массиве <массив меню> превышает количество строк в окне меню и если пользователь попытается переместить выделение за пределы окна верх или вниз, то элементы меню будут сдвигаться в окне (скроллинг). Надо отметить, что светящийся маркер не переходит автоматически в начало списка элементов, когда вы достигаете его конца, и не переходит в конец, когда вы достигаете начала списка. Однако, если нажать клавишу с какой-нибудь буквой, светящийся маркер переместится на строку меню, начинающуюся с этой буквы.

Перемещение по меню. ACHOICE() имеет два режима, зависящие от того, задан ли аргумент <функция пользователя> или нет. Если он не задан, активными являются следующие клавиши перемещения.

Клавиши ACHOICE() (Нет функции пользователя)
 -------------------------------------------------------------------
 Клавиша            Действие
 -------------------------------------------------------------------
 &lt;стрелка вверх&gt;    к предыдущему элементу
 &lt;стрелка вниз&gt;     к следующему элементу
 &lt;Home&gt;             к первому элементу меню
 &lt;End&gt;              к последнему элементу меню
 &lt;Ctrl&gt;-&lt;Home&gt;      к первому элементу в окне
 &lt;Ctrl&gt;-&lt;End&gt;       к последнему элементу в окне
 &lt;PgUp&gt;             к предыдущей странице
 &lt;PgDn&gt;             к следующей странице
 &lt;Ctrl&gt;-&lt;PgUp&gt;      к первому элементу меню
 &lt;Ctrl&gt;-&lt;PgDn&gt;      к последнему элементу меню
 &lt;Return&gt;           выбрать текущий элемент
 &lt;Esc&gt;              прервать выбор
 &lt;стрелка влево&gt;    прервать выбор
 &lt;стрелка вправо&gt;   прервать выбор
 &lt;первая буква&gt;     к элементу, начинающемуся с этой буквы
 -------------------------------------------------------------------
 

Цвет. Элементы меню отображаются в стандартом цвете, выделенный элемент - в выделенном цвете, недоступные элементы в невыбранном цвете. Например, следующий оператор установки цвета:

SETCOLOR("W+/N, BG+/B, , , W/N")

выводит меню как яркое-белое на черном, выделяемый элемент - ярко-бирюзовый на синем, а недоступные элементы меню - белые на черном.

Функция пользователя. Подобно другим функциям интерфейса с пользователем, ACHOICE() поддерживает функцию пользователя. Функция пользователя может быть использована при создании иерархических меню или переопределении клавишей.

Если задана функция пользователя, ACHOICE() автоматически отрабатывает только ограниченный набор клавиш. Они перечислены в таблице 5-2. Нажатие остальных клавиш приводит к передаче управления на функцию пользователя для их обработки. Управление также передается функции пользователя, когда ACHOICE() неактивна (т.е. когда больше нет клавиш для обработки).

Клавиши ACHOICE() (Функции пользователя заданы)
 -------------------------------------------------------------------
 Клавиша          Действие
 -------------------------------------------------------------------
 &lt;стрелка вверх&gt;  к предыдущему элементу
 &lt;стрелка вниз&gt;   к следующему элементу
 &lt;Ctrl&gt;-&lt;Home&gt;    к первому элементу в окне
 &lt;Ctrl&gt;-&lt;End&gt;     к последнему элементу в окне
 &lt;PgUp&gt;           к предыдущей странице
 &lt;PgDn&gt;           к следующей странице
 &lt;Ctrl&gt;-&lt;PgUp&gt;    к первому элементу меню
 &lt;Ctrl&gt;-&lt;PgDn&gt;    к последнему элементу меню
 -------------------------------------------------------------------
 

Когда ACHOICE() выполняет функцию пользователя, ей автоматически передаются следующие три параметра:

текущий режим ACHOICE()

текущий элемент в массиве меню

относительная позиция строки в окне меню.

Режим показывает текущее состояние ACHOICE(), зависящее от того, какая клавиша была нажата, и действие, предпринятое ACHOICE() перед выполнением функции пользователя. Параметр режима имеет следующие возможные значения:

Режимы ACHOICE()
 -------------------------------------------------------------------
 Режим    Achoice.ch      Описание
 -------------------------------------------------------------------
 0      AC_IDLE         неактивно
 1      AC_HITTOP       пытается продвинуть маркер вверх за список
 2      AC_HITBOTTOM    пытается продвинуть маркер за конец списка
 3      AC_EXCEPT       необрабатываемая клавиша
 4      AC_NOITEM       невыбранные элементы
 -------------------------------------------------------------------
 

После того, как функция пользователя будет выполнена, она должна вернуть в ACHOICE() код, определяющий последующие действия ACHOICE(). Ниже приводится набор этих кодов:

Значения, возвращаемые функцией пользователя ACHOICE().
 -------------------------------------------------------------------
 Значение   Achoce.ch    Действие
 -------------------------------------------------------------------
 0        AC_ABORT     прервать выбор
 1        AC_SELECT    сделать выбор
 2        AC_CONT      продолжить ACHOICE()
 3        AC_GOTO      к следующему элементу меню, первая буква
 которого совпадает с нажатой клавишей
 -------------------------------------------------------------------
 

<верхняя строка>

, <левая колонка>, <нижняя строка>, <правая колонка> определяют верхнюю левую и нижнюю правую координаты окна. Номера строк могут находиться в диапазоне от нуля до MAXROW() и номера колонок - в диапазоне от нуля до MAXCOL().

<массив меню>

- это массив символьных строк, которые высвечиваются как элементы меню. Каждый конкретный элемент меню в последствии идентифицируется своей числовой позицией в этом массиве.

<массив выбранных значений>

- это параллельный массив логических значений - каждый элемент этого массива соответствует одному элементу в массиве <массив меню> с тем же индексом. Элементы могут быть как логическими значениями, так и символьными строками. Если элемент - символьная строка, то она рассматривается как выражение, которое при вычислении должно выдать значение логического типа. В любом случае значение "ложь" (.F.) означает, что соответствующий элемент меню недоступен для выбора, а значение "истина" (.T.) означает, что он доступен. Если аргумент <выбираемость меню> задан в виде скаляра, а не массива, то его значение "ложь" (.F.) делает все элементы меню недоступными, а значение "истина" (.T.) - доступными. По умолчанию все элементы меню доступны для выбора.

<функция пользователя>

- это имя определенной пользователем функции, которая выполняется при нажатии нераспознаваемой клавиши. Имя функции задается как символьное выражение без круглых скобок и аргументов. Следует отметить, что поведение функции ACHOICE() при заданной функции пользователя отличается от поведения, когда она не задана. Более подробно об этом будет сказано ниже.

<позиция маркера>

- номер элемента в массиве <массив меню>, который будет выделен при начальном отображении меню. Если задан номер недоступного элемента меню или аргумент совсем не задан, то будет выделен первый доступный для выбора элемент в массиве.

<строка окна>

- номер строки окна, на которой появится первый элемент меню. Нумерация строк начинается с нуля. По умолчанию первый элемент меню появляется в такой строке окна, чтобы не оставалось пустых строк внизу. Таким образом, если существует достаточное количество элементов меню для заполнения окна, то первоначальный элемент появится на первой строке (нулевая строка) меню. Этот аргумент функции используется для управления первоначальным появлением меню, когда имеется больше элементов, чем вмещает окно. Как и во всех функциях, при пропуске необязательного аргумента вместо него надо записывать запятую.

Returns :

ACHOICE() возвращает числовую позицию выбранного в массиве <массив меню> элемента меню. Если процесс выбора прерван, то ACHOICE() возвращает нуль.

Function ALERT()

 ALERT( <сообщение> [,<массив предложений>] ) --> <номер предложения>

Функция ALERT() создает диалоговое окно. Это бывает полезно при обработке ошибок или в других ситуациях, где необходима пауза. Пользователь может перемещать выделенную строку нажатием клавиши <Пробел>, осуществить выбор нажатием клавиши <RETURN>, или клавиши, соответствующей первой букве выбираемого ответа. Если <массив предложений> не задан, то высвечивается предложение "OK" (да). ALERT() чувствительна к наличию или отсутствию xClipper-системы полноэкранного ввода-вывода. Если такая система отсутствует, то ALERT() использует стандартную систему телетайпного ввода-вывода.

Function FT_ACH2TB()

 FT_Ach2tb( <nToprow>,<nTopcol>[,<nBotrow>][,<nBotcol>],<aArrey>,     ;
 [<cBoxtype>],[<cBoxcolor>],[<cBoxtitle>],[<nTitlePos>],        ;
 [<cUselcolor>],[<cTitlecolor>],[<cBarcolor>],[<cHkcolor>],     ;
 [<lShadow>],[<lExecute>],[<nMsgrow>],[<nMsgcol>],              ;
 [<cMsg.color>],[cElevbar],[cEbarcolor],[<cEbarside>],          ;
 [<cNoSelcolor>],[<cTagch>],[<nStartelem>],[<lRscreen>],        ;
 [<nTimeout>],[<nTimeoutval>],[<cUserfunc>] )
 --> nOption
 

FT_Ach2tb() is a greatly enhanced, fully featured, and now mouse- supported replacement for Achoice(), based on a Tbrowse object. Each element of <aArray> (the array you pass to it) is itself an array. Each element can solely composed of "Option" (below), but may be composed as follows to take full advantage of the function's features:

Option , Message ,HotKeyPos,HotKeyColor,Selectable { "Utilities","System Utilities", 3 ,"+gr/b" ,.T. }

All elements except for the first, the option itself, are optional. IF 'Message' is NIL, no message is displayed. 'HotKeyPos' is the position within 'Option' of the hotkey. In the example above, the hotkey for 'Utilities' is the first 'i', i.e., at position 3. The default is 1. 'HotKeyColor' is the color to use for the hotkey display. The default is hiwhite on the current background color. 'Selectable' is a logical indicating whether or not that option can be selected. The default is .T.

The A_CHOICE() UDC in FT_ACH2T.CH makes using FT_ACH2TB() a breeze. The myriad of parameters can be written in any order. Only <nToprow>, <nTopcol>, and <aArrey> are required. See the example below.

There may be some confusion over 'unselected' and 'unselectable' options. The former refers to any option not currently covered by the selection bar. The latter refers to options you have designated unselectable in subelement 5 of <aArray>, i.e., by writing .F.

To enable tagging, pass any ASCII character as <cTagchar>. To tag/untag all options, press [SPACE]. To tag/untag individual options, press [+] and [-] respectively. On press of [+], browse moves to the next element in the display. To test for the tagged status of an option, use the WAS_TAGGED() UDC in FT_ACH2T.CH. To check the entire array for tags, use Aeval() in conjunction with Was_Tagged() as in the example below. When tagging is enabled, the string "Tags" will be written across the bottom row of the box in hiwhite on the current background color.

Because FT_ACH2TB() takes over the [SPACE],[+], and [-] keys, it saves any SET KEY procedures you might have set them to, and restores same on returning. Any other procedures you might have SET KEYs to will fly when FT_ACH2TB() is called...thanks to the Inkey() replacement, SKINkey().

The pice de resistance of FT_ACH2TB() is its ability to execute a user function designed entirely by you. It is called after each keypress, and because it is completely open-ended, extends the the reach of FT_ACH2TB() to the limits of Clipper. See the docu- mentation under <bUserfunc> above.

Test compile: CLIPPER ft_ach2t /n/w/m/dFT_TEST Test link : RTLINK FI ft_ach2t LIB nanfor /pll:base50

Mouse support

Mouse support is provided via the Nanforum Toolkit FT_M* functions. Most actions are tied to the left button. The equivalent of pressing [Esc] comes via the right button. These left button clicks will produce the designated actions:

Mouse cursor outside box : K_ENTER (select option)

Mouse cursor at box top left corner : browse:goTop()

bottom left corner : browse:goBottom()

top right corner : browse:pageUp()

bottom right corner : browse:pageDown()

Mouse cursor at option, tagging ENabled

Selection bar moves to option, subsequent press to tag or untag. Do this for as many options as you want to tag/untag, then move mouse cursor outside the box. Press again to select. Tagging overrides <lExecute>, so with tagging on and <lExecute> .F., subsequent presses while inside the box coordinates simply tag/untag.

Mouse cursor at option, tagging DISabled

IF <lExecute> is turned on, the option is immediately selected. If turned off, selection bar moves to option. Press again to select.

To Disable Mouse Support

Compile with /dNOMOUSE

<nToprow>

is the top row of the box to be drawn. Required.

<nTopcol>

is the top column of the box to be drawn. Required.

<nBotrow>

is the bottom row of the box to be drawn. The default is

<nToprow>

+Len(<aArrey>)+1 or maxrow()-2, whichever is less.

<nBotcol>

is the bottom column of the box to be drawn. The default is <nTopcol>+width of the widest element in <aArrey> +2. It's been pointed out that the number of commas required to default the <nBotrow> and <nBotcol> params. is at least slightly confusing. So, some documentation on the requirements: Default both: 7,9,, ARRAY: Default <nBotrow>, specify <nBotcol>: 7,9,,20 ARRAY: Default <nBotcol>, specify <nBotrow>: 7,9,15, ARRAY:

<aArrey>

is the arrey of options to present to the user. Each element can hold as many as five subelements, or as few as one. Required. Additional documentation below.

<cnBoxtype>

is the type of box to draw. Uses DispBox(). The default is a double-line box.

<cBoxcolor>

is the color with which to draw the box. The default is Setcolor().

<cBoxtitle>

is title of the box drawn on <nToprow>. The default is no title.

<nTitlepos>

is the starting column position (to the right of

<nTopcol>

) at which to draw <cBoxtitle>. The default is 1.

<cUselcolor>

is the color with which to draw unselected options. The default is Setcolor().

<cTitlecolor>

is the color with which to draw the box title. The default is yellow on red.

<cBarcolor>

is the color with which to draw the selection bar. The default is yellow on black.

<cHkcolor>

is the default color with which to draw the hotkeys for for each option. This is used when no hotkey color is supplied in <aArrey>. The default is hiwhite on the current background color.

<cShadow>

is a character string, either "L" or "R" (for left or right) to designate the side of the box where a shadow will appear. Leave this NIL to avoid drawing a shadow. You might also leave this NIL if you choose to use a .C or .ASM shadow function, which is a good idea. Shadoww(), included below, is flat-out SLOW.

<lExecute>

turn on/off execution of option when first letter is pressed. Rule: setting in element 5 of each <aArrey> subarray overrides <lexecute>. If that element is left NIL, the <lexecute> setting is used. If <lexecute> is not passed and element 5 is NIL, auto execution is turned ON.

<nMsgrow>

is the row on which to draw a message for each option. The default is two rows below the bottom of the box.

<nMsgcol>

is the column at which to draw a message for each option. The default is <nTopcol> +2. To CENTER the message, pass "C".

<cMsgcolor>

is the default color with which to draw messages. This color is used when element 4 of each <aArrey> subarray is left NIL. The default is Setcolor().

<cElevbar>

is the ASCII character to use as the elevator bar drawn on the box. Leave this NIL to draw no elevator bar.

<cEbarcolor>

is the color with which to draw the elevator bar. This is ignored if <cElevbar> is NIL.

<cEbarside>

is a character string, either "L" or "R" (for left or right) to designate the side of the box on which to draw the elevator bar. This is ignored if <cElevbar> is NIL.

<cNoselcolor>

is the color with which to draw unselectable options. The default is white on black.

<cTagchar>

is the ASCII character to use to draw tags that would appear to the right of each option. The default is *DIS*abled tagging. The default tag is chr(251).

<nStartelem>

is the number of the option where the selection bar will first be placed. Leave this NIL to begin at option 1.

<lRestscrn>

is a logical to designate whether or not the screen coordinates occupied by the box and/or shadow should be restored before FT_Ach2tb() returns. The default is .T.

<nTimeout>

is the number of seconds after which FT_ACH2TB() will timeout and return to the function/proced. which called it. The default is 0.

<nTimeoutVal>

is an optional alternative numeric value FT_ACH2TB() will RETURN when/if it times out. The default is the current element number.

<bUserfunc>

is a code block containing a function call to be executed after each key press. You need to write just two formal parameters to allow the run-time passing of the key pressed and the current element number, e.g.: { |key,num| Myfunc( key,num [,other params.] ) } Unlimited extra parameters may be passed. Of course, make certain to also write 'receptors' for them in 'Myfunc()' itself...as in the above example. The default is NO user function.

Returns :

the number of the selected option, or 0 if [Esc] is pressed.

Function FT_ADDER()

 FT_Adder()

PopAdder() gives you an adding machine inside your Clipper 5.2 application. It has the basic functions add, subtract, multiply, and divide. You may move it from one side of the screen to the other. It even displays a scrollable tape, if you want it.

There are a few HOT Keys while using the Adder:

<D>ecimals - change # of decimals <M>ove - the Adder from right display to left <T>ape - turn the Tape Display On or Off <S>croll - the tape display <DEL> --- -- 1st Clear entry -- 2nd Clear ADDER <ESC> - Quit <F10> - return a <TOTAL> to the active get

A couple of notes about the adder:

1.) It was designed to be used on an Enhanced keyboard with separate <DELETE> key. <DELETE> is used to clear the adder. However, it will still work on a Standard keyboard.

2.) You do not have to display the tape. You may turn it on at any time by pressing <T>. You may SCROLL back through the tape once there are more than 16 entries in the adder, by pressing <S>.

3.) To Quit the Adder just press <ESC>. To return your Total to the application press <F10>. The adder will place the Total in the active GET variable using oGet:VarPut(). The adder will only return a Total to a numerical GET!

4.) There are many support functions that you might find interesting. They are part of my personal library, but are necessary to the operation of the adder. You might want to pull these out to reduce the overall size of the adder. Many are worth at least a little time studying.

5.) To make FT_Adder a Hot key from inside your application at the beginning of your application add the line:

SET KEY K_ALT_A TO FT_Adder

This will make <ALT-A> a key "Hot" and permit you to Pop - Up the adder from anywhere in the application.

6.) If you use FT_INKEY(), you can even have active hotkeys in an INKEY().

Function FT_BLINK()

 FT_BLINK( <cMsg>, [ <nRow> ], [ <nCol> ] ) --> NIL

A quick way to blink a msg on screen in the CURRENT colors. Restores colors on return.

Function FT_BRWSWHL()

 FT_BRWSWHL( <aFields>, <bWhileCond>, <cKey>,                  ;
 [ <nFreeze> ], [ <lSaveScrn> ], [ <cColorList> ], ;
 [ <cColorShadow> ], [ <nTop> ], [ <nLeft> ],      ;
 [ <nBottom> ], [ <nRight> ] --> nRecno

This is a demonstration of TBrowse with a WHILE condition for an indexed database.

<aFields>

is array of field blocks of fields you want to display. Example to set up last name and first name in array: aFields := {} AADD(aFields, {"Last Name" , {||Names->Last} } ) AADD(aFields, {"First Name", {||Names->First} } )

<bWhileCond>

is the limiting WHILE condition as a block. Example 1: { ||Names->Last == "JONES" } Example 2: { ||Names->Last == "JONES" .AND. Names->First == "A" }

<cKey>

is the key to find top condition of WHILE. cLast := "JONES " cFirst := "A" Example 1: cKey := cLast Example 2: cKey := cLast + cFirst

<nFreeze>

is number of fields to freeze in TBrowse. Defaults to 0 if not passed.

<lSaveScrn>

is a logical indicating whether or not you want to save the screen from the calling program. Defaults to .T. if not passed.

<cColorList>

is a list of colors for the TBrowse columns. The 1st color is used as SAY/TBrowse Background and the 3rd and 4th colors are used as part of column:defColor := {3, 4} Thus if you pass a cColorList, you MUST pass at least 4 colors. Defaults to "N/W, N/BG, B/W, B/BG, B/W, B/BG, R/W, B/R" if not passed.

<cColorShad>

is the color of the TBrowse box shadow. Defaults to "N/N" if not passed.

<nTop>

, <nLeft>, <nBottom>, <nRight> are the coordinates of the area to display the TBrowse in. Defaults to 2, 2, MAXROW() - 2, MAXCOL() - 2 with shadowed box, i.e. full screen.

Returns :

nRecno is the number of the record selected by the <Enter> key. 0 is returned if there are either no records matching the WHILE condition or an <Esc> is pressed instead of an <Enter>

Function FT_CLRSEL()

 FT_ClrSel( <aClrData>, [ <lClrMode> ], [ <cTestChr> ] --> aClrData

This function allows users to select their own colour combinations for all the different types of screen I/O in a typical application. This facilitates an easy implementation of Ted Means' replacement of the @..PROMPT/MENU TO found in the NanForum Toolkit. If you are not using FT_MENUTO(), you can specify "A" for setting type and have a normal colour string returned.

Function FT_DISPMSG()

 FT_DISPMSG( <aMessageArray>, [ <cKey2Check> ],
 [ <nTopBoxRow> ], [ <nLeftBoxColumn> ],
 [ <cnBoxType> ], [ <lShadow> ] ) --> lKeyMatch

FT_DISPMSG() is a multi-purpose pop-up for user messages. Multiple lines may be displayed, each with a different attribute. The box will be automatically centered on the screen, or the row and/or column can be specified by the programmer. It also centers each line of the message within the box.

<aMessageArray>

is a multidimensional array of messages to be displayed and the color attributes for each message. The first dimension of the array contains one or more elements, each representing one line in the message box, up to the maximum number of rows on the screen. Within each line of the message individual characters or groups of characters may be delimited with braces ([]). The braces will be stripped out and the character(s) inside those braces will be highlighted. The second dimension of the array contains a color attribute for the corresponding element in dimension one, plus one additional element for the color of the box border. Dimension two will always contain one more element than dimension one. If an attribute is omitted, the last color selected will be used.

<Key2Check>

is a character string of one or more keys to check for. If omitted, the message is displayed and control is returned to the calling procedure. If one character is specified, FT_DISPMSG() waits for one keypress, restores the screen and returns. If multiple characters are specified, FT_DISPMSG() remains in a loop until one of the specified keys has been pressed, then restores the screen and returns.

<nTopBoxRow>

is the upper row for the message box. If omitted, the box is centered vertically.

<nLeftBoxColumn>

is the leftmost column for the box. If omitted, the box is centered horizontally.

<cnBoxType>

is a string of characters or a variable for the box border. See the DISPBOX() function. If omitted, a double box is drawn.

<lShadow>

is a logical variable. If true (.T.) or omitted, it uses FT_SHADOW() to add a transparent shadow to the box. If false (.F.), the box is drawn without the shadow.

Returns :

If <Key2Check> is not specified, FT_DISPMSG() will return false (.F.). If <Key2Check> is a one-character string, FT_DISPMSG() will return true (.T.) if the user presses that key, or false (.F.) if any other key is pressed. If <Key2Check> consists of multiple characters, it will lock the user in a loop until one of those keys are pressed and return the INKEY() value of the keypress.

Function FT_FILL()

 FT_FILL( <aSubArrayName>, <cMenuSelection>, <bFunction>,
 <lSelectable> ) --> NIL

FT_FILL() is a function used to set up the menu options prior to calling FT_MENU1().

Function FT_MENU1()

 FT_MENU1( <acBarNames>, <acOptions>, <acAction>,
 <acColors> [, <nTopRow> ], [ <lShadow> ] ) --> NIL

FT_MENU1() is a function that displays a pulldown menu for each item on the menu bar and executes the corresponding function for the item selected. When a called function returns false, FT_MENU1 returns control to the calling program.

Valid keystrokes and their corresponding actions:

Home - Activates Pulldown for first item on the menu bar End - Activates Pulldown for last item on the menu bar Left Arrow - Activates next Pulldown to the left Right Arrow - Activates next Pulldown to the right Tab - Same as Right Arrow Shift-Tab - Same as Left Arrow Page Up - Top item on current Pulldown menu Page Down - Bottom item on current Pulldown menu Enter - Selects current item Alpha Character - Moves to closest match and selects Alt-<Key> - Moves to corresponding menu bar item Escape - Prompts for confirmation and either returns to the calling routine or resumes

Example :

 // Declare arrays
 LOCAL aColors  := {}
 LOCAL aBar     := { " ENTER/EDIT ", " REPORTS ", " DISPLAY " }
 
 // Include the following two lines of code in your program, as is.
 // The first creates aOptions with the same length as aBar.  The
 // second assigns a three-element array to each element of aOptions.
 LOCAL aOptions[ LEN( aBar ) ]
 AEVAL( aBar, { |x,i| aOptions[i] := { {},{},{} } } )
 
 // fill color array
 // Box Border, Menu Options, Menu Bar, Current Selection, Unselected
 aColors := IF( lColor, {"W+/G", "N/G", "N/G", "N/W", "N+/G"}, ;
 {"W+/N", "W+/N", "W/N", "N/W","W/N"} )
 
 // array for first pulldown menu
 FT_FILL( aOptions[1], 'A. Execute A Dummy Procedure' , {|| fubar()}, .t. )
 FT_FILL( aOptions[1], 'B. Enter Daily Charges'       , {|| .t.},     .f. )
 FT_FILL( aOptions[1], 'C. Enter Payments On Accounts', {|| .t.},     .t. )
 
 // array for second pulldown menu
 FT_FILL( aOptions[2], 'A. Print Member List'         , {|| .t.},     .t. )
 FT_FILL( aOptions[2], 'B. Print Active Auto Charges' , {|| .t.},     .t. )
 
 // array for third pulldown menu
 FT_FILL( aOptions[3], 'A. Transaction Totals Display', {|| .t.},     .t. )
 FT_FILL( aOptions[3], 'B. Display Invoice Totals'    , {|| .t.},     .t. )
 FT_FILL( aOptions[3], 'C. Exit To DOS'               , {|| .f.},     .t. )
 
 Call FT_FILL() once for each item on each pulldown menu, passing it
 three parameters:
 
 FT_FILL( <cMenuSelection>, <bCodeBlock>, <lSelectable>
 
 <cMenuSelection> is a character string which will be displayed on
 the pulldown menu.
 
 <bCodeBlock> should contain one of the following:
 
 A function name to execute, which in turn should return .T. or .F.
 FT_MENU1 WILL RETURN CONTROL TO THE CALLING PROGRAM IF .F. IS
 RETURNED OR CONTINUE IF .T. IS RETURNED.
 
 .F. WHICH WILL CAUSE FT_MENU1 TO RETURN CONTROL TO THE CALLING
 PROGRAM.
 
 .T. WHICH WILL DO NOTHING.  THIS ALLOWS THE DEVELOPER TO DESIGN A
 SKELETON MENU STRUCTURE PRIOR TO COMPLETING ALL OF THE SUBROUTINES.
 
 // CALL FT_MENU1
 FT_MENU1( aBar, aOptions, aColors, 0 )
 
 NOTE: FT_MENU1() disables Alt-C and Alt-D in order to make them
 available for the menu bar.  It enables Alt-D and resets
 Alt-C to its previous state prior to calling each function.

Function FT_MENU2()

 FT_MENU2( <aMenuarray> [, <cColors> ] ) --> NIL

This function greatly simplifies the process of displaying light-bar menus. All prompts are padded out with spaces so they are the same length, a box is drawn around the prompts, the box is automatically centered on the screen, and the underlying screen is restored after a menu selection has been made.

Additionally, because you can tie action blocks to each menu option, you can save on a lot of DO CASE or IF..ELSEIF code in your main program. See the test code for a succinct demonstration.

Function FT_MENUTO()

 #include "FTMENUTO.CH"
 
 MENU TO <var> [COLD]

This enhanced version of MENU TO requires the inclusion of the header file FTMENUTO.CH in any source file that uses it. It may be used in place of the standard Clipper MENU TO command. However, in the interests of functionality it is NOT 100% compatible (in particular, you should make sure that the target memvar exists before executing the menu -- the Clipper version will create a PRIVATE memvar for you if it does not already exist, but this version does not). No whining! If compatibility is such a big deal then use the standard Clipper command.

Note that this command can also be called using function-style syntax. See the entry for FT_MENUTO() for further details.

Function FT_PENDING()

 FT_PENDING ( <cMsg>, [ <nRow> ], [ <nCol> ], ;
 [ <nWait> ], [ <cColor> ] ) --> NIL

A good way to display information messages during the running of an application is to send them all to the SAME line on the screen where users are expected to look for them. In order to give users a chance to read the current message before the next one is displayed we may need to insert a delay after each message.

FT_PENDING() function displays messages by keeping track of the time of the last message and providing a delay ONLY if the next pending message is issued much too soon after the current one.

Function FT_PICKDAY()

 FT_PICKDAY() --> cDayOfWeek

This function is ideal if you need the user to select a day.

Function FT_PROMPT()

 #include "FTMENUTO.CH"
 
 @ <nRow>, <nCol> PROMPT <cPrompt>                     ;
 [COLOR <cColor>]                     ;
 [MESSAGE <cMessage>]                 ;
 [MSGROW <nMsgRow>]                   ;
 [MSGCOL <nMsgCol>]                   ;
 [MSGCOLOR <cMsgColor>]               ;
 [TRIGGER <nTrigger>]                 ;
 [TRIGGERCOLOR <cTriggerColor>]       ;
 [HOME <nHome>]                       ;
 [END <nEnd>]                         ;
 [UP <nUp>]                           ;
 [DOWN <nDown>]                       ;
 [LEFT <nLeft>]                       ;
 [RIGHT <nRight>]                     ;
 [EXECUTE <bExec>]                    ;
 

Clipper's @...PROMPT and MENU TO commands are fine as far as they go. But many times you need more flexibility. As you'll no doubt notice if you read the argument list, this function is almost completely flexible. You can adjust locations and colors for every part of the prompt and its associated message. In addition, since you can control the effect of the arrow keys, you can allow both horizontal and vertical movement, or even disable certain arrow keys if you so desire. Support for nested menus is also available, since the prompts are stored in stack-based static arrays.

Note that this command can also be called using function-style syntax. See the entry for FT_PROMPT() for further details.

This enhanced version of @...PROMPT requires the inclusion of the header file FTMENUTO.CH in any source file that uses it. It is may be used in place of the standard Clipper @...PROMPT command. However, in the interests of functionality it is NOT 100% compatible. No whining! If compatibility is such a big deal then use the standard Clipper commands.

<nRow>

is the row at which the prompt is to appear.

<nCol>

is the column at which the prompt will appear.

<cPrompt>

is the menu item string.

<cColor>

is optional and is the color attribute of the prompt. Note that two colors are required; one for the standard setting and one for the enhanced setting (i.e. the light bar color). See the example below if this isn't clear. If <cColor> is not specified then the current SetColor() value is used by default.

<cMessage>

is optional and is the message associated with the prompt. If not specified, then no message will be displayed.

<nMsgRow>

is optional and is the row at which the message, if any, will appear. If not specified, the default is the current setting of the SET MESSAGE TO command.

<nMsgCol>

is optional and is the column at which the message, if any, will appear. If not specified, the default is either zero or centered, depending on the current setting of the CENTER option of the SET MESSAGE TO command.

<cMsgColor>

is optional and is the color attribute of the message. If not specified, the default is the same as the prompt color.

<nTrigger>

is optional and is the position within the prompt string where the trigger character is located. If not specified, the default is one.

<cTriggerColor>

is optional and is the color attribute of the trigger character. Note that two colors are required; one for the standard setting and one for the enhanced setting (i.e. the light bar color). See the example below if this isn't clear. If <cTriggerColor> is not specified then the default is the same color as the rest of the prompt.

<nHome>

is optional and specifies which prompt becomes active when the home key is pressed. If not specified, the default is the first prompt.

<nEnd>

is optional and specifies which prompt becomes active when the end key is pressed. If not specified, the default is the last prompt.

<nUp>

is optional and specifies which prompt becomes active when the up arrow key is pressed. If not specified, the default is the previous prompt. The current setting of SET WRAP TO is obeyed.

<nDown>

is optional and specifies which prompt becomes active when the down arrow key is pressed. If not specified, the default is the next prompt. The current setting of SET WRAP TO is obeyed.

<nRight>

is optional and specifies which prompt becomes active when the right arrow key is pressed. If not specified, the default is the next prompt. The current setting of SET WRAP TO is obeyed.

<nLeft>

is optional and specifies which prompt becomes active when the left arrow is pressed. If not specified, the default is the previous prompt. The current setting of SET WRAP TO is obeyed.

<bExec>

is optional and is a code block to evaluate whenever the menu item to which it belongs is selected.

Returns :

NIL

Function FT_SLEEP

 FT_SLEEP( <nSeconds>, [<nInitial>] ) --> nil

This routine will wait a specified period of time. It provides resolution based upon the execution of the SECONDS() function. It does not use an input state such as INKEY(). The specified time is the minimum time sleeping and will usually be slightly longer.

The second optional argument allows one to begin timing an event prior to executing some operation. This is useful when, for example, you input a key or mouse click and wish to do something but still want to note if the user double entered (mouse or key) within a certain time which in turn may have meaning within your program's context.

The routine correctly handles passing through midnight but will not work for more than 24 hours.

Function FT_XBOX()

 FT_XBOX( [ <cJustType> ], [ <cRetWait> ], [ <cBorType> ],   ;
 [ <cBorColor> ], [ <cBoxColor> ], [ <nStartRow> ], ;
 [ <nStartCol> ], <cLine1>,  <cLine2>, <cLine3>,    ;
 <cLine4>, <cLine5>, <cLine6>, <cLine7>, <cLine8> ) --> NIL

FT_XBOX() allows the programmer to display a message box on the screen without needing to calculate the dimensions of the box. Only the upper left corner needs to be defined. The function will calculate the lower right corner based on the number and length of strings passed.

A maximum of eight strings can be displayed. If a string is too long to fit on the screen it is truncated.

The first seven parameters are optional. The default settings are: Lines of text are centered. Control is returned to the calling routine immediately. A single line border is painted. The border is black on white. The text is white on black. The box is centered both vertically and horizontally.

WARNING: Shadowing is achieved by a call to FT_SHADOW(), an assembly routine not found in this .PRG. In order to use XBOX, SHADOW.OBJ must also be present somewhere (if you are using NANFOR.LIB, then it is).