Custom TextBox cursor/caret

In roblox I’m creating a physical terminal that sits in front of my character on a surface gui. I have keystroke events and automatically numbered lines down, but there’s one more thing I want. I want a frame to represent where my text cursor (I believe it’s called a caret) is for other players.

I’ve no clue where to start. There aren’t many posts about this and none of them have been helpful. I’ve looked into TextBox.CursorPosition but that only returns a single number and I’m not sure how you’d convert that to offset.

Would appreciate to know a method to do this or if it’s even possible with what roblox provides us.

1 Like
local Game = game
local Script = script
local TextService = Game:GetService("TextService")
local TextBox = Script.Parent
local Frame = TextBox.Parent:WaitForChild("Frame")
Frame.Size = UDim2.new(0, 1, 0, TextBox.TextSize)
Frame.BackgroundColor3 = Color3.new(0, 0, 0)
Frame.Visible = false

local function OnTextBoxTextChanged()
	local TextSize = TextService:GetTextSize(string.sub(TextBox.Text, 1, TextBox.CursorPosition), TextBox.TextSize, TextBox.Font, Vector2.new(0, math.huge))
	Frame.Position = UDim2.new(0, TextBox.Position.X.Offset + (TextBox.Size.X.Offset / 2) + (TextSize.X / 2) + 2, 0, TextBox.Position.Y.Offset + (TextBox.Size.Y.Offset / 2) - TextBox.TextSize / 2)
end

local function OnTextBoxFocused()
	task.spawn(OnTextBoxTextChanged)
	while TextBox:IsFocused() do
		Frame.Visible = not Frame.Visible
		task.wait(0.5)
	end
end

local function OnTextBoxFocusLost()
	Frame.Visible = false
end

TextBox:GetPropertyChangedSignal("Text"):Connect(OnTextBoxTextChanged)
TextBox.Focused:Connect(OnTextBoxFocused)
TextBox.FocusLost:Connect(OnTextBoxFocusLost)

TextBoxCursor.rbxl (34.7 KB)
https://gyazo.com/69c5ff673390598493db1ffe60827387

1 Like