Skip to content

User Interface

This section contains all functions that involve directly interacting with the user, be that by showing a window, checking the state of a key, or placing data onto the users clipboard. These handle generic input such as from the keyboard, and also generic output such as an alert box.

Window management notes:

Enums

key_code

This is a complete list of possible keycodes in NVGT, as well as a short description of what they are. These are registered in the key_code enum, meaning you can use this type to pass any value listed here around though it is also safe to use unsigned integers.

Letter keys

Number keys

Special keys

Function keys

Arrow keys

Numpad keys

Modifier keys

Miscellaneous keys

Media keys

Browser and Application keys

Additional keys

key_modifier

This is a complete list of supported key modifiers and their descriptions. These are registered in the key_modifier enum, so you can use that type to pass any value listed here around.

Example:

void main() {
	show_window("Example");
	wait(50); // Give the screen readers enough time to speak the window title before speaking.
	screen_reader_output("Press alt+f4 to close this window.", true);
	while (true) {
		wait(5);
		if (keyboard_modifiers & KEYMOD_ALT > 0 && key_pressed(KEY_F4))
			exit();
	}
}

message_box_flags

This is an enumeration of possible flags to be passed to the message_box(), alert(), question(), and similar functions.

touch_device_type

These are the possible types of touch input devices.

window_flags

An enumeration of flags that can be used with the show_window function to control the window's appearance.

Events

Besides polling functions such as key_pressed(), NVGT can notify your code when input arrives by calling functions you register with an event. Each event is a global property, such as on_key_press, that holds a list of listeners. Whenever the event happens, NVGT calls the listeners one at a time, in the order they appear in the list.

Events are delivered while NVGT processes input, which happens during calls such as wait() and refresh_window(). Polling and events can be used together: registering a listener doesn't stop functions like key_pressed() from working.

Adding listeners

A listener can be any of the following:

Add a listener with the += operator, or with the insert() method, which also lets you choose its position in the list:

bool insert(listener@ listener, int index = -1);

An index of -1 adds the listener to the end of the list, while 0 makes it the first listener to be called. Both += and insert() return false if the listener is already in the list.

Removing listeners

Remove a listener with the -= operator or with remove(listener). You can also remove the listener at a given position with remove(uint index), or every listener with clear(). To find a listener's position in the list, use find(listener), which returns -1 if it is not in the list. The count property holds the number of listeners.

Object listeners and method listeners only hold a weak reference to their object, so being registered with an event doesn't keep an object alive. Once the object is destroyed, its listener is removed automatically the next time the event fires.

Available events

on_characters

An event that is fired whenever the user types text.

engine_character_event on_characters;

Listener signatures:

Arguments passed to listeners:

Remarks:

Unlike the key events, this event receives the actual text produced by the keyboard, taking the keyboard layout, shift state and input methods into account. Although the argument is called character, it can contain more than one character, for example when an input method for Chinese or Japanese inserts a whole word at once.

Text input must be active for this event to fire. It is started automatically when your window is shown, except on platforms with a screen keyboard, where you need to call start_text_input() (see SCREEN_KEYBOARD_SUPPORTED).

The same text is also returned by get_characters(), so you can use either approach.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

string typed;
void on_text(string text) {
	typed += text;
	screen_reader_output(text, true);
}
void main() {
	show_window("Example");
	on_characters += on_text;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Type something, then press enter to hear all of it. Press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_pressed(KEY_RETURN)) {
			screen_reader_output(typed.empty() ? "Nothing typed" : typed, true);
			typed = "";
		}
	}
}

on_key_press

An event that is fired whenever a key is pressed down.

engine_key_event on_key_press;

Listener signatures:

Arguments passed to listeners:

Remarks:

This fires once when a key goes down. While the key is held, the operating system's key repeats fire on_key_repeat instead.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

bool on_key(int key) {
	if (key == KEY_ESCAPE) exit();
	screen_reader_output(get_key_name(key), true);
	return true;
}
void main() {
	show_window("Example");
	on_key_press += on_key;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Press any key to hear its name, or escape to exit.", true);
	while (true) wait(5);
}

on_key_release

An event that is fired whenever a key is released.

engine_key_event on_key_release;

Listener signatures:

Arguments passed to listeners:

Remarks:

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

class key_timer : engine_key_event_listener {
	timer held;
	void on_key_press(int key) {
		if (key == KEY_SPACE) held.restart();
	}
	void on_key_release(int key) {
		if (key == KEY_SPACE) screen_reader_output("Held for " + held.elapsed + " milliseconds", true);
	}
}
void main() {
	show_window("Example");
	key_timer kt;
	on_key_press += kt;
	on_key_release += kt;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Hold and release space to hear how long you held it. Press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) wait(5);
	on_key_press -= kt;
	on_key_release -= kt;
}

on_key_repeat

An event that is fired each time the operating system repeats a key that is being held down.

engine_key_event on_key_repeat;

Listener signatures:

Arguments passed to listeners:

Remarks:

The first press of a key fires on_key_press, not this event. The delay before repeating starts, and the speed of the repeats, come from the user's keyboard settings.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

int repeats = 0;
void on_repeat(int key) {
	if (key == KEY_SPACE) repeats++;
}
void main() {
	show_window("Example");
	on_key_repeat += on_repeat;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Hold space, then release it to hear how many times it repeated. Press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_released(KEY_SPACE)) {
			screen_reader_output(repeats + " repeats", true);
			repeats = 0;
		}
	}
}

on_touch_finger_cancel

An event that is fired when a touch is interrupted instead of ending normally.

engine_touch_event on_touch_finger_cancel;

Listener signatures:

Arguments passed to listeners:

Remarks:

The operating system cancels a touch when something else takes it over, for example a system gesture or a notification appearing. When this happens, on_touch_finger_up is not fired for that finger, so treat this event as the end of the touch but don't act on it as if the user had finished a tap.

The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

void on_cancel(uint64 device, const touch_finger& finger) {
	screen_reader_output("Touch canceled", true);
}
void main() {
	show_window("Example");
	on_touch_finger_cancel += on_cancel;
	while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}

on_touch_finger_down

An event that is fired whenever a finger touches a touch device.

engine_touch_event on_touch_finger_down;

Listener signatures:

Arguments passed to listeners:

Remarks:

The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

void on_down(uint64 device, const touch_finger& finger) {
	screen_reader_output("Touched at " + round(finger.x * 100, 0) + " percent across, " + round(finger.y * 100, 0) + " percent down", true);
}
void main() {
	show_window("Example");
	on_touch_finger_down += on_down;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Touch the screen to hear where you touched it. Press escape or back to exit.", true);
	while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}

on_touch_finger_move

An event that is fired whenever a finger moves while touching a touch device.

engine_touch_motion_event on_touch_finger_move;

Listener signatures:

Arguments passed to listeners:

Remarks:

The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

float swipe_x = 0;
void on_move(uint64 device, const touch_finger& finger, float relative_x, float relative_y) {
	swipe_x += relative_x;
}
void on_up(uint64 device, const touch_finger& finger) {
	if (swipe_x > 0.2) screen_reader_output("Swiped right", true);
	else if (swipe_x < -0.2) screen_reader_output("Swiped left", true);
	swipe_x = 0;
}
void main() {
	show_window("Example");
	on_touch_finger_move += on_move;
	on_touch_finger_up += on_up;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Swipe left or right. Press escape or back to exit.", true);
	while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}

on_touch_finger_up

An event that is fired whenever a finger is lifted from a touch device.

engine_touch_event on_touch_finger_up;

Listener signatures:

Arguments passed to listeners:

Remarks:

If the touch is interrupted rather than ending normally, on_touch_finger_cancel is fired instead of this event.

The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.

See the Events topic for how listeners are added, ordered and removed, and what their return values mean.

Example:

class tap_counter : engine_touch_event_listener {
	int taps = 0;
	void on_touch_finger_up(uint64 device, const touch_finger& finger) {
		taps++;
		screen_reader_output(taps + (taps == 1 ? " tap" : " taps"), true);
	}
}
void main() {
	show_window("Example");
	tap_counter counter;
	on_touch_finger_up += counter;
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Tap the screen to count taps. Press escape or back to exit.", true);
	while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
	on_touch_finger_up -= counter;
}

Functions

alert

Display a message box with an OK button to the user.

int alert(const string&in title, const string&in text, bool can_cancel = false, uint flags = 0);

Arguments:

Returns:

int: the number of the button that was pressed, either OK or cancel.

Example:

void main() {
	alert("Hello", "I am a standard alert");
	alert("Hi", "And I'm a cancelable one", true);
}

android_request_permission

Request a permission from the Android operating system either synchronously or asynchronously.

bool android_request_permission(string permission, android_permission_request_callback@ callback = null, string callback_data = "");

Arguments:

Returns:

bool: true if the request succeeded (see remarks), false otherwise or if this function was not called on Android.

Remarks:

The callback signature this function expects is registered as : funcdef void android_permission_request_callback(string permission, bool granted, string user_data);

This function behaves very differently depending on whether you've provided a callback or not. If you do not, this function blocks the thread that called it until the user responds to the permission request, in which case it returns true or false depending on whether the user has actually granted the permission. On the other hand if you do provide a callback, the instant return value of this function only indicates whether the request has been made rather than whether the permission has been granted, as that information will be provided later in the given callback.

Beware that the callback you provide might get invoked on any thread, thus the provision of a more simple, blocking alternative. If you do provide a callback, you are responsible for handling any data races that may result.

android_show_toast

Shows an Android toast notification, small popups that are unique to that operating system.

bool android_show_toast(const string&in message, int duration, int gravity = -1, int x_offset = 0, int y_offset = 0);

Arguments:

Returns:

bool: true if the toast was shown, false otherwise or if called on a platform other than Android.

Remarks:

Learn more about android toasts notifications here.

clipboard_get_text

Returns the text currently on the user's clipboard.

string clipboard_get_text();

Returns:

string: The text on the user's clipboard, as UTF_8.

Example:

void main() {
	string text = clipboard_get_text();
	if (text == "")
		alert("Info", "Your clipboard is empty");
	else
		if (text.length() > 1024)
			alert("Info", "Your clipboard contains a long string. It is " + text.length() + " characters");
		else
			alert("Info", "Your clipboard contains " + text);
}

clipboard_set_raw_text

Sets the text on the user's clipboard, using the system encoding.

bool clipboard_set_raw_text(const string&in text);

Arguments:

Returns:

Bool: true on success, false on failure.

Remarks:

To copy UTF-8 text, see clipboard_set_text().

Example:

void main() {
	string text = input_box("Text", "Enter the text to copy.");
	clipboard_set_raw_text(text);
	if (text == "")
		alert("Info", "Your clipboard has been cleared.");
	else
		alert("Info", "Text copied");
}

clipboard_set_text

Sets the text on the user's clipboard.

bool clipboard_set_text(const string&in text);

Arguments:

Returns:

Bool: true on success, false on failure.

Remarks:

To copy text in the system encoding, see clipboard_set_raw_text().

Example:

void main() {
	string text = input_box("Text", "Enter the text to copy.");
	clipboard_set_text(text);
	if (text == "")
		alert("Info", "Your clipboard has been cleared.");
	else
		alert("Info", "Text copied");
}

destroy_window

Destroys the currently shown window, if it exists.

bool destroy_window();

Returns:

bool: true if the window was successfully destroyed, false otherwise.

Example:

void main() {
	alert("Info", "Pressing SPACE will destroy the window");
	show_window("Example");
	while (true) {
		wait(5); // Don't hog all the CPU time.
		if (key_pressed(KEY_SPACE)) {
			destroy_window();
			wait(2000); // Simulate doing things while the window isn't active.
			exit();
		}
	}
}

exit

Completely shut down your application, returning a particular exit code to your operating system in the process.

void exit(int exit_code = 0);

Arguments:

Example:

void main() {
	show_window("Example");
	screen_reader_output("Press escape to exit.", true);
	while (true) {
		wait(5);
		if (key_pressed(KEY_ESCAPE)) {
			screen_reader_output("Goodbye.", true);
			wait(500);
			exit();
		}
	}
}

focus_window

Attempt to bring your NVGT window to the foreground.

bool focus_window();

Returns:

bool: true if the window was successfully focused, false otherwise.

Example:

void main() {
	timer focuser;
	show_window("Focus every 5 seconds example");
	while (true) {
		wait(5);
		if (key_pressed(KEY_ESCAPE)) exit();
		if (focuser.has_elapsed(5000)) {
			focuser.restart();
			focus_window();
		}
	}
}

get_characters

Determine any printable characters typed into the games window since this function's lass call.

string get_characters();

Returns:

string: Any characters typed since this function was last called, or an empty string if none are available.

Remarks:

This is the function one would use if they wished to integrate a virtual text field of any sort into their games or applications.

Unlike functions such as key_down or keys_pressed, this function focuses specifically on textual content which has been input to the application. A character returned from this function, for example, could be anything from the space bar to an emoticon inserted using the windows emoji picker.

A typical use case would involve calling this function once per iteration of your game loop and storing any new characters that are typed into a buffer that composes a chat message or a username or anything else requiring virtual text input.

Example:

void main() {
	string buffer;
	show_window("get_characters example");
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		string char = get_characters();
		if (!char.empty()) {
			buffer += char;
			screen_reader_speak(char, true); // You need to process this further for screen readers, such as replacing . with period and other punctuation.
		}
		if (key_pressed(KEY_RETURN)) {
			screen_reader_speak("You typed " + (!buffer.empty()? buffer : "nothing"), true);
			buffer = "";
		}
	}
}

get_touch_device_name

Determine the name of a touch device given it's ID.

string get_touch_device_name(uint64 device_id);

Returns:

string : The name of the given device, or an empty string on failure.

get_touch_device_type

Determine the type of a touch device given it's ID.

touch_device_type get_touch_device_name(uint64 device_id);

Returns:

touch_device_type: The type of the given device, or TOUCH_DEVICE_TYPE_INVALID if a bad ID is given.

get_touch_devices

Enumerate all available touch input devices on the system.

uint64[]@ get_touch_devices();

Returns:

uint64[]@: An array of touch device IDs, may be empty of no touch devices are available.

Remarks:

You can pass any of the IDs returned from this function to the get_touch_device_type, get_touch_device_name, or query_touch_device functions.

Note that on some platforms, certain touch devices might not become available until they first receive input. For example this is true with the Android touch screen.

Example:

void main() {
	uint64[]@ devices = get_touch_devices();
	if (devices.length() < 1) {
		alert("no devices", "There are no detectable touch devices on your system.");
		exit();
	}
	for (uint i = 0; i < devices.length(); i++)
		alert("device " + devices[i], get_touch_device_name(devices[i]));
}

get_window_height

Gets the height of the game window in pixels.

int get_window_height();

Returns:

int: The height of the window in pixels, or 0 if no window is currently open.

Example:

void main() {
	show_window("Window Size Example");
	wait(50); // Give the window time to appear
	int width = get_window_width();
	int height = get_window_height();
	alert("Window Size", "The window is " + width + " pixels wide and " + height + " pixels high.");
}

get_window_os_handle

Returns the native handle used by the operating system to manage NVGT's window.

uint64 get_window_os_handle();

Returns:

uint64: An HWND / NSWindow* / similar handle that the operating system uses to manage the window.

Remarks:

This function is only useful for someone trying to do something advanced, usually involving passing the identifier for the game window to a system API function or something similar. If you don't understand what this function does, you should probably avoid it for the present.

Example:

void main() {
	// Lets set the window title using the windows API, typically you'd use show_window a second time for this.
	show_window("hello");
	uint64 handle = get_window_os_handle();
	library lib;
	lib.load("user32");
	lib.call("int SetWindowTextA(uint64, ptr)", handle, "example window");
	wait(500); // Let the user observe the change before exiting.
}

get_window_text

Returns the title of your window.

string get_window_text();

Returns:

string: the title of your window.

Example:

void main() {
	string[] possible_titles = {"Hello world", "NVGT test", "My game", "Example", "Window title example"};
	show_window(possible_titles[random(0, possible_titles.length() - 1)]);
	while (true) {
		wait(5);
		if (key_pressed(KEY_ESCAPE)) exit();
		if (key_pressed(KEY_SPACE)) {
			screen_reader_output("The window title currently is: " + get_window_text(), true);
			show_window(possible_titles[random(0, possible_titles.length() - 1)]); // Randomize the title again.
		}
	}
}

get_window_width

Gets the width of the game window in pixels.

int get_window_width();

Returns:

int: The width of the window in pixels, or 0 if no window is currently open.

Example:

void main() {
	show_window("Window Size Example");
	wait(50); // Give the window time to appear
	int width = get_window_width();
	int height = get_window_height();
	alert("Window Size", "The window is " + width + " pixels wide and " + height + " pixels high.");
}

idle_ticks

Obtain the time passed in milliseconds since a user has pressed a key or used the mouse.

uint64 idle_ticks();

returns

uint64: the number of milliseconds since a user has last interacted with the machine.

remarks

This function can serve as a useful utility to verify whether a user has been away from the keyboard.

It is currently integrated for windows and MacOS. On linux, it will always return 0 until further notice.

Example:

void main() {
	int64 t;
	show_window("Idle test");
	wait(50);
	screen_reader_speak("Press space to check the idle time and escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_pressed(KEY_SPACE))
			screen_reader_speak("You have been idle for %0 milliseconds".format(t), true);
		t = idle_ticks();
	}
}

info_box

Displays a dialog to the user consisting of a read-only text field and a close button.

bool info_box(const string&in title, const string&in label, const string&in text, uint64 flags = 0);

Arguments:

Returns:

bool: true if the user pressed the close button, false otherwise.

Example:

void main() {
	info_box("Test", "Information", "this is a\r\nlong string\r\nthat can be split\r\nacross lines");
}

input_box

Displays a dialog to the user consisting of an input field, an OK button and a cancel button.

string input_box(const string&in title, const string&in text, const string&in default_text = "", uint64 flags = 0);

Arguments:

Returns:

string: the text that the user typed.

Example:

void main() {
	string name = input_box("Name", "What is your name?", "John Doe");
	if (name.is_empty()) {
		alert("Error", "You didn't type a name, unidentified person!");
		exit();
	}
	alert("Hi", name + "!");
}

install_keyhook

Attempts to install NVGT's JAWS keyhook.

bool install_keyhook(bool allow_reinstall = true);

Arguments:

Returns:

bool: true if the keyhook was successfully installed, false otherwise.

Remarks:

This keyhook allows NVGT games to properly capture keyboard input while the JAWS for Windows screen reader is running.

Note that installing it when JAWS is not running may yield unintended consequences, such as functionality of other screen readers being slightly limited while in your game window.

Example:

void main() {
	bool success = install_keyhook();
	if (success) {
		alert("Info", "The keyhook was successfully installed!");
		uninstall_keyhook();
	}
	else
		alert("Info", "The keyhook was not successfully installed.");
}

is_console_available

Determine if your application has access to a console window or not.

bool is_console_available();

Returns:

bool: true if your application has access to a console window, false otherwise.

Remarks:

If this function returns false, it is very likely that any output passed to the print or println functions or the cout/cerr datastreams will be silently dropped.

Example:

void main() {
	if (is_console_available()) println("hello from the console!");
	else alert("console unavailable", "hello from the user interface!");
}

is_window_active

Determines if your game's window is active (i.e. has the keyboard focus).

bool is_window_active();

Returns:

bool: true if your game window has the keyboard focus, false if not.

Example:

void main() {
	show_window("Test");
	wait(1000); // Give the user time to alt+tab away if they so choose.
	bool active = is_window_active();
	if (active)
		alert("Info", "Your game window is active.");
	else
		alert("Info", "Your game window is not active.");
}

is_window_hidden

Determines if your game's window is hidden or not.

bool is_window_hidden();

Returns:

bool: true if your game window is hidden, false if it's shown.

Example:

void main() {
	show_window("Test");
	bool hide = random_bool();
	if (hide) hide_window();
	alert("The window is", is_window_hidden() ? "hidden" : "shown");
}

key_down

Determine if a particular key is held down.

bool key_down(uint key);

Arguments:

Returns:

bool: true if the key is down at all, false otherwise.

Remarks:

For a complete list of keys that can be passed to this function, see input constants.

Example:

void main() {
	show_window("Example");
	while (true) {
		wait(5);
		if (key_down(KEY_SPACE))
			screen_reader_output("space", true);
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

key_pressed

Determine if a particular key is pressed.

bool key_pressed(uint key);

Arguments:

Returns:

bool: true if the key was just pressed, false otherwise.

Remarks:

For a complete list of keys that can be passed to this function, see input constants.

Example:

void main() {
	show_window("Example");
	while (true) {
		wait(5);
		if (key_pressed(KEY_SPACE))
			screen_reader_output("You just pressed space!", true);
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

key_released

Determine if a particular key was just released.

bool key_released(uint key);

Arguments:

Returns:

bool: true if the key was just released, false otherwise.

Remarks:

For a complete list of keys that can be passed to this function, see input constants.

Example:

void main() {
	show_window("Example");
	while (true) {
		wait(5);
		if (key_released(KEY_SPACE))
			screen_reader_output("you just released the space key", true);
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

key_repeating

Determine if a particular key is repeating (i.e. it's being held, but wasn't just pressed).

bool key_repeating(uint key);

Arguments:

Returns:

bool: true if the key is repeating, false otherwise.

Remarks:

For a complete list of keys that can be passed to this function, see input constants.

Example:

void main() {
	show_window("Example");
	while (true) {
		wait(5);
		if (key_repeating(KEY_SPACE))
			screen_reader_output("space", true);
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

key_up

Determine if a particular key is up.

bool key_up(uint key);

Arguments:

Returns:

bool: true if the key is up, false otherwise.

Remarks:

For a complete list of keys that can be passed to this function, see input constants.

Example:

void main() {
	int last_spoken = ticks(); // Speak periodically to avoid overwhelming the user (or their screen reader).
	show_window("Example");
	while (true) {
		wait(5);
		if (key_up(KEY_SPACE) && (ticks() - last_spoken) >= 500) {
			last_spoken = ticks();
			screen_reader_output("space is up", true);
		}
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

keys_down

Returns a handle to an array of keys that are held down.

uint[]@ keys_down();

Returns:

uint[]@: a handle to an array containing keys that are held down.

Remarks:

For a complete list of keys that can be returned by this function, see input constants.

keys_pressed

Returns a handle to an array of keys that were just pressed.

uint[]@ keys_pressed();

Returns:

uint[]@: a handle to an array containing keycodes that were just pressed.

Remarks:

For a complete list of keys that can be returned by this function, see input constants.

keys_released

Returns a handle to an array of keys that were just released.

uint[]@ keys_released();

Returns:

uint[]@: a handle to an array containing keycodes that were just released.

Remarks:

For a complete list of keys that can be returned by this function, see input constants.

message_box

Displays a customizable message box.

int message_box(const string&in title, const string&in text, string[]@ buttons, uint flags = 0);

Arguments:

Returns:

int: the number of the button that was pressed, according to its position in the buttons array.

Remarks:

Notes on button syntax:

Example:

void main() {
	message_box("Hello there", "I am a message box with two buttons", {"`OK", "~Cancel"});
}

mouse_down

Determine if a particular mouse button is being held down.

bool mouse_down(uint8 button);

Arguments:

*uint8 button: The button to check.

Returns:

bool: True if the mouse button is being held, false otherwise.

Example:

void main()
{
while(true)
{
wait(5);
if(mouse_down(1))
{
screen_reader_output("Left click is being held!");
}
if(key_pressed(KEY_ESCAPE))
{
exit();
}
}
}

mouse_pressed

Determine if a particular mouse button is pressed.

bool mouse_pressed(uint8 button);

Arguments:

*uint8 button: The mouse button to check.

returns:

bool: If the specified mouse button was pressed.

Example:

void main()
{
show_window("Example");
while(true)
{
wait(5);
if(mouse_pressed(1))
{
screen_reader_output("You just pressed left click!");
}
if(key_pressed(KEY_ESCAPE))
{
exit();
}
}
}

open_file_dialog

Displays a dialog from which a user may select a file to open.

string open_file_dialog(string filters = "", string default_location = "")

Arguments:

Returns:

string: The path to a file or an empty string on failure/cancelation.

Remarks:

The file extension filters are specified in the format description:extension|description:extension|description:extension1;extension2;extension3... You can also use the filter * as an all files filter. for example: audio files:mp3;wav;ogg|text files:txt;rtf;md|all files:* would produce 3 items in the file type combo box, those being audio files, text files and all files.

On some platforms it might be possible for the user to select a file that does not yet exist, so you should check for that condition yourself after the user selects a file just to be safe if that is important to you.

This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.

You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.

Example:

void main() {
	string location = open_file_dialog("NVGT scripts:nvgt", cwdir());
	if (location.empty()) return;
	alert("example", "you selected " + location);
}

query_touch_device

Check what fingers are in contact with a touch device and where they are on the screen, if any.

touch_finger[]@ query_touch_device(uint64 device_id = 0);

Arguments:

Returns:

touch_finger[]@: An array of structures containing touch coordinates and pressure (see remarks).

Remarks:

Each structure in the returned array represents a finger, thus the length of the array indicates how many fingers are touching the device.

Touch_finger objects contain only 4 properties. Int64 id is a unique identifier of the finger that will remain the same as long as the finger touches the devices, float x and float y contain the coordinates of the finger on the device, and the float pressure property indicates how much force or pressure the finger is being applied to the device with.

Usage of this structure other than to receive touch input is not endorsed by the NVGT developers and may lead to unexpected results, most notably creating a touch_finger instance manually will likely set it's properties to random uninitialized memory on the stack. You have been warned.

Example:

void main() {
	// Report the number of fingers touching the device.
	show_window("touch example");
	tts_voice tts;
	int prev_finger_count = 0;
	tts.speak("ready", true);
	while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) {
		wait(5);
		touch_finger[]@ fingers = query_touch_device(); // This will query the last device that was touched.
		if (fingers.length() != prev_finger_count) {
			tts.speak(fingers.length() + (fingers.length() != 1? " fingers" : " finger"), true);
			prev_finger_count = fingers.length();
		}
	}
}

question

Display a yes/no dialog box to the user.

int question(const string&in title, const string&in text, bool can_cancel = false, uint flags = 0);

Arguments:

Returns:

int: the number of the button that was pressed (1 for yes, 2 for no).

Example:

void main() {
	int res = question("Hello there", "Do you like pizza?");
	alert("Info", "You clicked " + (res == 1 ? "yes" : "no"));
}

refresh_window

Updates the game window, pulling it for any new events and responding to messages from the operating system.

void refresh_window();

Remarks:

You do not need to call this function yourself so long as you use the recommended wait() function in your game's loops, as wait() implicitly calls this function. We provide refresh_window() standalone unless you want to use your own / a different sleeping mechanism such as nanosleep, in which case you do need to manually pull the window using this function.

For the main game window, the first refresh presents an initial black frame if nothing has been drawn yet. The same happens after showing a hidden window if no new drawing is pending. Later refreshes present only drawing that has not already been shown. If you call game_window.present() yourself, the next wait() or refresh_window() will not present that frame a second time.

For UI windows to function on the vast mejority of operating systems, they must maintain a constant stream of communication between the operating system and the program that created them. If a window stops receiving and handling such communications for even a few seconds, it will first become laggy before the operating system decides that the window has gone dead and begins reporting that the application is in a not responding or busy state.

To solve this problem in NVGT applications, refresh_window() is provided to do all of this message handling for you in one repeated function call. This function will pull the operating system for any new messages or events and process them, updating the states of functions like key_pressed, get_characters etc. If it is not repeatedly called in some way, your entire application will be disfunctional.

run

Allows for running exsacutable files from within your program.

bool run(const string&in filename, const string&in arguments, bool wait_for_completion, bool background);

Arguments:

*bool background: Determines if a window is displayed.

Returns

bool: True if the executable was launched successfully.

Example:

void main()
{
//Opens notepad.
run("notepad.exe","",false,false);
}

save_file_dialog

Displays a dialog from which a user may select a location to save a file.

string save_file_dialog(string filters = "", string default_location = "")

Arguments:

Returns:

string: The path to save to or an empty string on failure/cancelation.

Remarks:

The file extension filters are specified in the format description:extension|description:extension|description:extension1;extension2;extension3... You can also use the filter * as an all files filter. for example: audio files:mp3;wav;ogg|text files:txt;rtf;md|all files:* would produce 3 items in the file type combo box, those being audio files, text files and all files.

Keep in mind that the user may select a file that already exists if they wish to overwrite it.

This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.

You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.

Example:

void main() {
	string location = save_file_dialog("text files (*.txt):txt|all files:*");
	if (location.empty()) return;
	alert("example", "you selected " + location);
}

select_folder_dialog

Displays a dialog from which a user may select a folder.

string select_folder_dialog(string default_location = "")

Arguments:

Returns:

string: The path to a folder or an empty string on failure/cancelation.

Remarks:

Be aware that on some platforms, the user might be able to select a directory that does not yet exist.

This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.

You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.

Example:

void main() {
	string location = select_folder_dialog();
	if (location.empty()) return;
	alert("example", "you selected " + location);
}

set_application_name

This function lets you set the name of your application. This is a name that's sent to your operating system in certain instances, for example in volume mixer dialogs or when an app goes not responding. It does not effect the window title or anything similar.

bool set_application_name(const string&in application_name);

Arguments:

Returns:

bool: true if the name was successfully set, false otherwise.

show_window

Shows a window with the specified title.

bool show_window(const string&in title, uint flags = 0);

Arguments:

Returns:

bool: true if window creation was successful, false otherwise.

Remarks:

This window doesn't do any event processing by default. As such, you have to create a loop in order to keep it alive.

Example:

void main() {
	alert("Info", "Press escape to close the window.");
	show_window("Example", WINDOW_FLAG_RESIZABLE | WINDOW_FLAG_MAXIMIZED);
	while (true) {
		wait(5); // Don't hog all the CPU.
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

total_keys_down

Returns the total number of keys that are currently or have just been held down.

int total_keys_down();

Returns:

int: the number of keys currently or recently held down.

Remarks:

This function includes not only keys that are currently being held down, but also keys that have just been released within the last frame. It's purpose is to reduce the worklow of keyboard configuration systems that want to detect how many keys to monitor, including key releases.

Example:

void main() {
	int check_time = 1000, orig_ticks = ticks();
	show_window("Example");
	while (true) {
		wait(5);
		if ((ticks() - orig_ticks) >= check_time) {
			orig_ticks = ticks();
			int key_count  = total_keys_down();
			screen_reader_output(key_count + " " + (key_count == 1 ? "key is" : "keys are") + " currently held down.", true);
		}
		if (key_pressed(KEY_ESCAPE))
			exit();
	}
}

uninstall_keyhook

Uninstall's NVGT's JAWS keyhook.

void uninstall_keyhook();

Remarks:

This keyhook allows NVGT games to properly capture keyboard input while the JAWS for Windows screen reader is running.

Example:

void main() {
	install_keyhook();
	alert("Info", "Keyhook installed. Uninstalling...");
	uninstall_keyhook();
	alert("Done", "Keyhook uninstalled.");
}

urlopen

Opens the specified URL in the appropriate application, for example an https:// link in your web browser, or a tt://link in TeamTalk.

bool urlopen(const string&in url);

Arguments:

Returns:

bool: true if the URl was successfully opened, false otherwise.

Remarks:

What application this function opens depends on what the user has set on their system; there's no way for you to control it.

Example:

void main() {
	urlopen("https://nvgt.dev");
}

wait

Waits for a specified number of milliseconds.

void wait(int milliseconds);

Arguments:

Remarks:

This function blocks the calling thread, meaning no other work can happen on that thread until the wait period is over.

On the main thread, it performs other essential tasks, such as incremental garbage collection, internal event processing, and refreshing the window.

It is strongly advised to always put wait(5); in your main loops. This prevents your game from hogging the CPU, and also makes sure that the window remains responsive and has been updated with the latest input events from the user.

Please note that, due to low-level operating system scheduling behaviors, the millisecond parameter is not an exact value, but rather a guaranteed minimum. This is even more important to remember when calling from the main thread given the additional tasks performed. It should therefore never be used as a time marker where accuracy is required.

Example:

void main() {
	alert("Info", "Once you press OK, I will wait for 2000 milliseconds (2 seconds).");
	wait(2000);
	alert("Info", "2000 milliseconds passed!");
}

Global Properties

cursor_visible

Shows or hides the mouse cursor, or determines whether it is currently visible.

bool cursor_visible;

Remarks:

Hiding the cursor only stops it from being drawn, the mouse still moves and generates input as normal. To keep the mouse inside your game's window, see mouse_grab.

This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false.

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Press space to show or hide the mouse cursor, or escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_pressed(KEY_SPACE)) {
			cursor_visible = !cursor_visible;
			screen_reader_output(cursor_visible ? "Cursor shown" : "Cursor hidden", true);
		}
	}
}

KEYBOARD_AVAILABLE

Determines whether a keyboard is connected to the device.

const bool KEYBOARD_AVAILABLE;

Remarks:

This is mainly useful on mobile devices, where your game might want to offer touch controls when no physical keyboard is attached.

This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false even if a keyboard is connected.

To list the connected keyboards, see get_keyboards().

Example:

void main() {
	show_window("Example");
	alert("Keyboard", KEYBOARD_AVAILABLE ? "A keyboard is connected." : "No keyboard is connected.");
}

keyboard_modifiers

Gets or sets the modifier keys, such as shift, control and the lock keys, that are currently active.

key_modifier keyboard_modifiers;

Remarks:

The value is a combination of the flags in the key_modifier enum. To check for a particular modifier, combine this value with the flag using the & operator and compare the result against 0, for example (keyboard_modifiers & KEYMOD_SHIFT) != 0. Remember the parentheses, because comparison operators are evaluated before &.

The KEYMOD_CTRL, KEYMOD_SHIFT, KEYMOD_ALT and KEYMOD_GUI values match either the left or the right version of their key.

Setting this property changes the modifier state that NVGT reports, but does not press or release any keys on the user's keyboard. This can be useful to clear a modifier that your game no longer wants to treat as held, for example after showing a dialog.

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Press space, optionally while holding shift or control. Press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (!key_pressed(KEY_SPACE)) continue;
		string held;
		if ((keyboard_modifiers & KEYMOD_SHIFT) != 0) held += "shift ";
		if ((keyboard_modifiers & KEYMOD_CTRL) != 0) held += "control ";
		screen_reader_output(held.empty() ? "Space" : held + "space", true);
	}
}

MOUSE_ABSOLUTE_X, MOUSE_ABSOLUTE_Y and MOUSE_ABSOLUTE_Z

The current position of the mouse within your game's window, and the total distance its wheel has scrolled.

Remarks:

MOUSE_ABSOLUTE_X and MOUSE_ABSOLUTE_Y are the mouse coordinates relative to the top left corner of your window. They are updated whenever the mouse moves over the window, and are 0 until it does. MOUSE_ABSOLUTE_Z starts at 0 and adds up every scroll of the mouse wheel. Scrolling away from the user usually increases it, though the direction is reversed if the operating system is set to reverse scrolling.

Unlike MOUSE_X, MOUSE_Y and MOUSE_Z, these properties don't depend on mouse_update(). They are updated as input arrives, which happens during calls such as wait().

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Click anywhere in the window to hear where you clicked, or press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (mouse_pressed(1))
			screen_reader_output(round(MOUSE_ABSOLUTE_X, 0) + ", " + round(MOUSE_ABSOLUTE_Y, 0), true);
	}
}

MOUSE_AVAILABLE

Determines whether a mouse is connected to the device.

const bool MOUSE_AVAILABLE;

Remarks:

This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false even if a mouse is connected.

To list the connected mice, see get_mice().

Example:

void main() {
	show_window("Example");
	alert("Mouse", MOUSE_AVAILABLE ? "A mouse is connected." : "No mouse is connected.");
}

mouse_grab

Confines the mouse to your game's window, or determines whether it is currently confined.

bool mouse_grab;

Remarks:

While the mouse is grabbed, the cursor can't leave the window, which is useful for games that are controlled by moving the mouse. This only has an effect while your game window exists, so set it after calling show_window(). Without a window, it reads false.

This is the same setting as window.mouse_grab.

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Press space to grab or release the mouse, or escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_pressed(KEY_SPACE)) {
			mouse_grab = !mouse_grab;
			screen_reader_output(mouse_grab ? "Mouse grabbed" : "Mouse released", true);
		}
	}
}

MOUSE_X, MOUSE_Y and MOUSE_Z

How far the mouse has moved, and how far its wheel has scrolled, between the two most recent calls to mouse_update().

Remarks:

MOUSE_X and MOUSE_Y are the horizontal and vertical distance the mouse moved, in window coordinates. Positive values mean right and down. MOUSE_Z is how far the mouse wheel scrolled, where positive values usually mean the wheel was scrolled away from the user. If the operating system is set to reverse the scrolling direction (often called natural scrolling), the sign is reversed as well. Some mice and touchpads scroll in fractions of a step.

These values are only recalculated when you call mouse_update(), which is not called automatically. Call it once per iteration of your game loop, after wait(), and then read these properties. Calling mouse_update() more than once per iteration splits the movement between the calls, so later calls see smaller values.

To get the mouse position rather than how far it moved, see MOUSE_ABSOLUTE_X, MOUSE_ABSOLUTE_Y and MOUSE_ABSOLUTE_Z.

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Scroll the mouse wheel, or press escape to exit.", true);
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		mouse_update();
		if (MOUSE_Z > 0) screen_reader_output("Scrolled up", true);
		else if (MOUSE_Z < 0) screen_reader_output("Scrolled down", true);
	}
}

SCREEN_KEYBOARD_SUPPORTED

Determines whether the platform provides an on-screen keyboard, such as the virtual keyboard on a phone or tablet.

const bool SCREEN_KEYBOARD_SUPPORTED;

Remarks:

On platforms with a screen keyboard, text input is not started automatically when your window is shown, because doing so would cover part of the screen with the keyboard. Call start_text_input() when your game wants the user to type, and stop_text_input() when it is done. On other platforms, text input is started automatically by show_window().

To check whether the screen keyboard is currently showing, see is_screen_keyboard_shown().

Example:

void main() {
	show_window("Example");
	alert("Screen keyboard", SCREEN_KEYBOARD_SUPPORTED ? "This device has a screen keyboard." : "This device does not have a screen keyboard.");
}

window

A handle to your game's main window, which gives access to more window settings than the global window functions provide.

game_window@ window;

Remarks:

This property is read only. It is null until a window has been created with show_window(), and becomes null again after destroy_window(). Check for null before using it if your code can run without a window.

Through this handle you can, for example, change the window's title, size and position, make it fullscreen, or draw text and shapes into it. See the game_window class for everything it offers.

Example:

void main() {
	show_window("Example");
	wait(50); // Give screen readers time to speak the window title.
	screen_reader_output("Press space to change the window title, or escape to exit.", true);
	int presses = 0;
	while (!key_pressed(KEY_ESCAPE)) {
		wait(5);
		if (key_pressed(KEY_SPACE)) {
			presses++;
			window.set_title("Space pressed " + presses + (presses == 1 ? " time" : " times"));
			screen_reader_output(window.title, true);
		}
	}
}