Skip to content

Change Window Opacity Using a Linux Gtk Declare

You can call into Linux APIs to use methods and properties that are not built into the framework by using the Declare command. To create a Declare statement you first need to track down the API you want to use using Linux documentation.

The Linux API is largely based on the C/C++ programming language and makes heavy use of structures.

As a simple example, the gtk_widget_set_opacity method in libgtk-3 can be used to change the window opacity so that it appears more transparent. This is what the method declaration looks like in the Gnome docs:

void
gtk_widget_set_opacity (GtkWidget *widget,
 double opacity);

This tells you it is a method (sub) because the “void” at the beginning indicates it does not return a value. The first parameter is a pointer to a GtkWidget, which in this case is the handle to the Xojo window. The opacity is a Double in the range of 0 to 1.

So the above method call translates to a Declare that looks like this:

Declare Sub gtk_widget_set_opacity Lib "libgtk-3" (handle As Integer, opacity As Double)

To set the window to 75% opacity you can call it like this:

gtk_widget_set_opacity(Self.Handle, 0.75)

Because this method is called for a window, you can put it in a Xojo Extension Method to make it easier to call. To do this, create a global method on a module like this:

Public Sub Opacity(Extends w As Window, value As Double)
  #If TargetLinux Then
    Declare Sub gtk_widget_set_opacity Lib "libgtk-3" (handle As Integer, opacity As Double)
     gtk_widget_set_opacity(w, value)
  #EndIf
End Sub

Note the use of the “#If TargetLinux” line. This prevents this code from being compiled into Windows or macOS builds of your app where the code could possible crash your app.

This now allows you to have code like this on a window’s Open event to center the window:

Self.Opacity(0.75)

To learn more in the Xojo Documentation:

If there are Linux-related or other topics, regarding Xojo Programming or general technology, you are interested in reading about on the Xojo Blog about please let us know!