Skip to content

How To Create a Custom Button Control in Xojo – Part 4: Adding Focus

In part 3 of this series we made our CanvasButton inspector-friendly by exposing all our colors, corner radius and other properties. Today we’re going to wire up real keyboard focus so that you can:

  • Tab to the button
  • See a neat focus ring when it has focus
  • Grab focus on click

1. Track the Focus State

Add a private property to keep track of whether the button has focus:

  Private IsFocused As Boolean = False

2. Respond to Focus Events

Implement FocusReceived and FocusLost so we can set/clear the flag and force a redraw:

  Sub FocusReceived()
    If Enabled And AllowFocusRing Then
      IsFocused = True
      Refresh(False)
    End If
  End Sub

  Sub FocusLost()
    If Enabled And AllowFocusRing Then
      IsFocused = False
      Refresh(False)
    End If
  End Sub

3. Grab Focus on Mouse Click

Modify your MouseDown to call SetFocus. Now clicking the button also gives it focus immediately:

  Function MouseDown(x As Integer, y As Integer) As Boolean
    #Pragma unused x
    #Pragma unused y

    If Enabled Then
      IsPressed = True
      SetFocus       // ← new
      Refresh(False)
      Return True
    Else
      Return False
    End If
  End Function

4. Draw an Inset Focus Ring

In the Paint event, after drawing the border, add:

// … after the border code …
If IsFocused And AllowFocusRing Then
  g.DrawingColor = Color.HighlightColor
  g.PenSize = 1
  // Inset by 2px so it sits inside the border
  g.DrawRoundRectangle(2, 2, g.Width-4, g.Height-4, CornerRadius-2, CornerRadius-2)
End If

5. Enable Canvas Focus

By default, DesktopCanvas won’t accept focus, so make sure to check AllowFocusRing in the Inspector when you drop CanvasButton onto a window.

Try It Out

  1. Run the app:
    • Tab to the button → you’ll see the focus ring

What’s Next?

Stay tuned for more awesome updates!

You can grab the latest source on GitHub: GitHub – CanvasButton

More in this series:

Gabriel is a digital marketing enthusiast who loves coding with Xojo to create cool software tools for any platform. He is always eager to learn and share new ideas!