Using Declares In Your Multi-Platform Desktop Apps

Published September 15, 2014 by
Xojo

Sometimes you need a feature that is not available directly from the Xojo framework. Responding to this need is what Declares are designed for: to get access to system native APIs. On OS X, you typically look at the Cocoa APIs. On Windows, the Win32 APIs. Finally on Linux, the GTK APIs.

As an example, let’s say we desperately need to add transparency to one of your application windows. Here is how to proceed.

Find the Native API Documentation

You need to get to the right documentation for each native API.

COCOA

The source for Cocoa API is https://developer.apple.com/. Since we are looking for a window functionality, NSWindow is the class we need to review this, in which we’ll find our target ObjC method:

- (void)setAlphaValue:(CGFloat)windowAlpha

WIN32

The source for Win32 API is http://msdn.microsoft.com. Again, we want to focus on window functionalities, http://msdn.microsoft.com/en-us/library/windows/desktop/ms633540(v=vs.85).aspx in which we’ll find our target C function:

GTK

The source for GTK API is http://developer.gimp.org/api/2.0/gtk/. Here again, we want to review functions related to GTKWindow http://developer.gimp.org/api/2.0/gtk/GtkWindow.html, in which we’ll find our target C method:

void gtk_window_set_opacity (GtkWindow *window, gdouble opacity);

Map to Xojo Code

In order to avoid wasting time understanding how these methods/functions work in real situation, it’s always efficient to google around to figure out how they are implemented in native code. There are tons of sample code you can review via Google. This way, you’ll figure out our Win32 call need an other one in order to work correctly: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx declared this way:

Most of the tricky part of using Declares is the ability to convert a C/C++/ObjC type to a type Xojo can handle. Fortunately, Xojo Documentation helps a lot. It provides detailed information about how to define a Declare, and a very handy types correspondences table.

Let’s start with Cocoa

Native, Objective-C method:- (void)setAlphaValue:(CGFloat)windowAlpha

CGFloat (in that case, possible values are 0.0 to 1.0) can be handled by the Xojo type Single

In order to get this method working, your Linux environment must run a composite manager. If not, this method will silently fail. If you want to check it before executing this method, add a Declare like this:

if gtk_widget_is_composited(Self.Handle) then gtk_window_set_opacity(Self.Handle, 0.4)end if

Setting up all together in your app.

Since these declares are designed to be compiled depending of the target platform, our code should be placed into pragma directives that indicate the compiler what should be taken in account depending of the current platform you are building for: