November
2nd
2013

Maximized borderless Unity application
by

Sometimes it can be necessary to start your Unity application as a maximized borderless window: one advantage is that it will allow you to start other applications above your game.

One situation is, by example, you want to allow the user of a touchscreen computer to write any text inside your game by launching a virtual keyboard app. In this case, using a borderless full-screen window is that raising the keyboard window does not disturb then game but will still continue running in the background to process keyboard input, and will regain focus automatically as soon as the keyboard is dismissed (see this link).

The following script, by being attached to a game object, will allow you to make your application borderless. Moreover, you can also set it to be fullscreen/maximized or at a defined size.

This script only works for a standalone windows application.

using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
using UnityEngine;

/// <summary>
/// Allow a standalone windows application to run without border at a specific screen position or in fullscreen.
/// You can also use the command argument -popupwindow in order to do the same thing with less control.
/// This allows you to run other program over your unity application (as by example a virtual keyboard).
/// </summary>
[ExecuteInEditMode]
public class BorderlessMode : MonoBehaviour
{
	public Rect ScreenPosition;
	public bool IsFullscreen = false;
 
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
	[DllImport("user32.dll")]
	static extern IntPtr SetWindowLong (IntPtr hwnd, int  _nIndex, int  dwNewLong);

	[DllImport("user32.dll")]
	static extern bool SetWindowPos (IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

	[DllImport("user32.dll")]
	static extern IntPtr GetForegroundWindow ();
 
	const uint SWP_SHOWWINDOW = 0x0040;
	const int GWL_STYLE = -16;
	const int WS_BORDER = 1;
 
	void Start ()
	{
		if(IsFullscreen)
			ScreenPosition = GetFullscreenResolution();
		SetWindowLong (GetForegroundWindow (), GWL_STYLE, WS_BORDER);
		bool result = SetWindowPos (GetForegroundWindow (), 0, (int)ScreenPosition.x, (int)ScreenPosition.y, (int)ScreenPosition.width, (int)ScreenPosition.height, SWP_SHOWWINDOW);
	}
#endif
	
#if UNITY_EDITOR
	void Update() {
		if(IsFullscreen)
			ScreenPosition = GetFullscreenResolution();
	}
#endif

	Rect GetFullscreenResolution() {
		Resolution resolution = Screen.currentResolution;
		return new Rect(0f, 0f, (float) resolution.width, (float) resolution.height);
	}
 
}

Leave a Reply

Your email address will not be published.