UserInputService WindowFocused event fires when the window of the Roblox client gains focus - typically when the Roblox client is maximized/actively open on the user’s screen.
For example, the code below prints “Window focused” whenever the Roblox client gains focus.
local UserInputService = game:GetService("UserInputService") UserInputService.WindowFocused:Connect(function() print("Window focused") end)
This event can be used alongside
UserInputService/WindowFocusReleased to track whether the Roblox client is actively focused on a user’s screen.
As this event only fires locally, it can only be used in a
Window Focus AFK Script
This example fires a
RemoteEvent/FireServer|RemoveEvent to the server name AfkEvent when the
LocalPlayer’s client gains or loses focus.
The purpose of this code sample is to fire a server-side event to indicate when the player is AFK. This is indicated by spawning a
ForceField around the player when the client loses focus and
Instance/Destroy|destroying the forcefield when the client gains focus.
In order for this example to work as expected, the code labelled LocalScript must be placed in a
LocalScript and the code labelled Script must be placed in a
-- LocalScript local Players = game:GetService("Players") local player = Players.LocalPlayer local UserInputService = game:GetService("UserInputService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local AfkEvent = ReplicatedStorage:WaitForChild("AfkEvent") local function focusGained() AfkEvent:FireServer(false) end local function focusReleased() AfkEvent:FireServer(true) end UserInputService.WindowFocused:Connect(focusGained) UserInputService.WindowFocusReleased:Connect(focusReleased) -- Script local ReplicatedStorage = game:GetService("ReplicatedStorage") local AfkEvent = Instance.new("RemoteEvent") AfkEvent.Name = "AfkEvent" AfkEvent.Parent = ReplicatedStorage local function setAfk(player, afk) if afk then local forcefield = Instance.new("ForceField") forcefield.Parent = player.Character else local forcefield = player.Character:FindFirstChildOfClass("ForceField") if forcefield then forcefield:Destroy() end end end AfkEvent.OnServerEvent:Connect(setAfk)