Accessing DOS environment variables with 16 or 32bit PB applications.

Back Up Next

Author: Eric Aling
Accessed:

Sometimes, you need to access DOS environment variables. PB does not provide a function for this so we have to do this ourself. You could implement this by using a DLL but I'd rather stick with PowerBuilder. Instead of DLLs, we use the native Windows API functions. For 16bit, you can't access the environment variables in one go. This is because a string is returned with '0' characters, representing a delimiter. With PB, this means 'end of the string'. With a trick, we can jump to the next value in the string. We do that as long as we have not found what we're looking for. Check it out:

16 bit way

External functions:

FUNCTION long GetDosEnvironment() Library "krnl386.exe"
FUNCTION string AnsiUpper(long lAddress) Library "user.exe"

Create a function for accessing a wanted environment variable. Declaration:

string f_getenvironment ( as_var )

Code:

int iLen
long lRet
string sValue
/* get the 'address' of the first environment variable */
lRet = GetDosEnvironment()
/* add '=' to the environment variable where looking for. This is for searching in the string */
as_Var = Upper(as_Var) + "="
/* get the current lenght of the variable */
iLen = len(as_Var)
/* lRet points to the start of a string. With AnsiUpper(), we get the string */
sValue = AnsiUpper(lRet) 
DO WHILE sValue <> ""
/* check if the string is what where looking for. If so, return the part after the '=' sign */
IF left(sValue + "=", iLen) = as_Var THEN RETURN mid(sValue, iLen + 1)
/* else, move lRet to the next variable in the string */
lRet += Len(sValue) + 1
sValue = AnsiUpper(lRet) 
LOOP
/* nothing found, return error */
RETURN "error"

 

32 bit way

In 32bit Windows environments, it's more simple because a better Windows API function is provided (Watch out: CaSeSenSiTiVe):

FUNCTION long ExpandEnvironmentStringsA(
REF String lpszSrc,
REF string lpszDest,
long cchDest ) library "kernel32.dll"

This function replaces in the total environment string, all occurrences idientified by %ourvariable% with it's according value. Easy, so create the same function like:

string f_getenvironment ( as_var )

and code:

string ls_dest
ls_dest = space(128)
long ll_ret
/* put our wanted variable within the percentage signs */
as_var = '%' + as_var + '%'
/* get it */
ll_ret = ExpandEnvironmentStringsA(as_var,ls_dest,127)
/* check */
IF ll_ret <= 0 THEN
RETURN "error"
ELSE
RETURN ls_dest
END IF

 

That's all there is to it. Enjoy!

Back Up Next