Current User

BlitzPlus Forums/BlitzPlus Programming/Current User

Arem(Posted 2005) [#1]
Anybody know how to tell what user is currently logged in?


Phil Newton(Posted 2005) [#2]
You need to use userlibs to do this. I apologise if I go into too much detail. First create a decls file in BlitzPlus/userlibs called "advapi32.decls", and paste the following into it.

.lib "advapi32.dll"

;;; <summary>Gets the name of the currently logged in user and places it in a bank.</summary>
;;; <param name="lpBuffer">Bank to place username data into.</param>
;;; <param name="nSize">Bank containing max size of name to retrieve.</param>
;;; <returns>Non-zero value if read correctly. lpBuffer will contain string data and nSize will contain the number of bytes read.</returns>
AdvApi32_GetUserName%(lpBuffer*, nSize*):GetUserNameA


You can use that on its own to get the username, but I've written a nicer function to wrap it. Code is below.

;;; <summary>Specifies the maximum size of username that can be retrieved.</summary>
;;; <subsystem>Blitz.Windows.AdvApi32</subsystem>
Const AA32_GETUSERNAME_MAXSIZE% = 256

;;; <summary>Gets the username of the user currently logged into Windows.</summary>
;;; <returns>String containing currently logged in user.</returns>
;;; <subsystem>Blitz.Windows.AdvApi32</subsystem>
Function AA32_GetUserName$()
	
	Local userName$			;;; Username retrieved
	Local bnk_Username%		;;; Bank containing username data
	Local bnk_Size%			;;; Bank containing size of username
	
	; Create size bank and set max username size to AA32_GETUSERNAME_MAXSIZE
	bnk_Size = CreateBank(4)
	PokeInt(bnk_Size, 0, AA32_GETUSERNAME_MAXSIZE)
	
	; Create string data bank
	bnk_Username = CreateBank(AA32_GETUSERNAME_MAXSIZE)
	
	; Call the API - it puts characters into bnk_username and size info into bnk_Size
	AdvApi32_GetUserName%(bnk_Username, bnk_Size)
	
	; Read each byte from data bank, and convert to character data
	; We subtract one as bnk_Size is one char longer to take into account the 
	; null terminator character.
	For i = 0 To PeekInt(bnk_Size, 0) - 1
		userName = userName + Chr$(PeekByte(bnk_Username, i))
	Next
	
	; Cleanup & return username
	FreeBank(bnk_Username)
	FreeBank(bnk_Size)
	
	Return userName$
	
End Function


So all you have to do is call "AA32_GetUserName$" and the rest is done for you.

Hope that helps!