Skip to content

C++Builder code snippet - get current name for Windows, OSX and iOS

I was reading a StackOverflow question and answer in the Delphi group and spotted this one: "How to get the currently logged in username". Here is a C++Builder XE5 version of similar coding that gets the logged in user name Windows and Mac OSX. For iOS the code gets the iPhone’s name using the Objective-C bridge.

//---------------------------------------------------------------------------
#include <fmx.h>
#pragma hdrstop
#include "DesktopMainForm.h"
#if defined(TARGET_OS_IPHONE)
#include <iOSapi.UIKit.hpp>
#endif
#if defined(TARGET_OS_MAC)
#include <Posix.Unistd.hpp>
#endif
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.fmx"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::GetUserNameButtonClick(TObject *Sender)
{
	// code for Mac OS X
	#if defined(TARGET_OS_MAC)
	UserNameLabel->Text = getlogin();  / use the posix getlogin function
	// code for iOS
	#if defined(TARGET_OS_IPHONE)
	_di_UIDevice device = TUIDevice::Wrap(TUIDevice::OCClass->currentDevice());
	UserNameLabel->Text = device->name()->cString();
	#endif
	// code for Win32 and Win64
	#if defined(_WIN32) || defined(_WIN64)
	wchar_t buf[300];
	DWORD bufSize = sizeof(buf);
	bool success = ::GetUserName(buf,&bufSize);  // use the Windows API "GetUserName" function
	(buf,bufSize);
	if (success)
		UserNameLabel->Text =  String(buf);
	else
		UserNameLabel->Text = "Unable to get user name.";
	#endif
}

Here is a simple main form with a TButton and TLabel.

To build the desktop project use "File | New | FireMonkey Desktop Application - C++Builder". Put a TButton and TLabel on the form. Add the TButton’s OnClick event handler and use the code above in your form’s source code. To build the mobile version of the project use "File | New | FireMonkey Mobile Application - C++Builder". Put a TButton and TLabel on the form. Add the TButton’s OnClick event handler and use the code above in your form’s source code. Here is the project group in the IDE Project Window.

The desktop application works on Win32, Win64 and OSX.

The mobile application works on iOS.

A little bit of C++ code for each platform and you are good to go.

Bad Behavior has blocked 4 access attempts in the last 7 days.

Close