Modificare l'aspetto del cursore del mouse

Da Gambas-it.org - Wikipedia.

E' possibile modificare l'aspetto del cursore (o anche detto puntatore) del mouse sia quando il cursore è all'interno di una finestra dell'applicazione Gambas, sia quando esso è al di fuori.


Modificare l'aspetto del cursore del mouse quando esso è all'interno di una finestra dell'applicazione Gambas

Quando il cursore del mouse è all'interno di una finestra dell'applicazione Gambas, ne può essere modificato l'aspetto mediante le risorse di Gambas medesimo.

Vi sono alcune modalità.

Uso della Proprietà ".Mouse" di un Controllo grafico

Vi sono vari Oggetti grafici che posseggono la Proprietà ".Mouse", alla quale va assegnato un valore che rappresenta un particolare aspetto grafico del puntatore del Mouse.
Se il puntatore del Mouse entra all'interno di quel Controllo grafico, esso muta il suo aspetto in quello stabilito dal valore assegnato alla Proprietà ".Mouse".

E' possibile impostare questo comportamento dall'inizio prevedendolo ad esempio nell'Evento "_Open()" della Classe Form:

Public Sub Open_Form()

' Se il puntatore del Mouse entra all'interno del "Form", muta il suo aspetto in una "croce":
  Me.Mouse = Mouse.Cross

End

oppure anche usando l'Evento "_Enter() di uno specifico Oggetto grafico:

Public Sub TextArea1_Enter()
 
 TextArea1.Mouse = Mouse.Cross
  
End

In tal caso il puntatore del mouse, quando entrerà nell'area di tale Controllo grafico, vedrà mutare il proprio aspetto.


Uso della Classe Cursor

La Classe Cursor consente di attribuire al puntatore del Mouse un'immagine.

In particolare, in fase di creazione della variabile di tipo Cursor, va assegnata ad essa una Picture contenente l'immagine che si utilizzerà per il nuovo aspetto del cursore del mouse. Tale variabile, poi, sarà assegnata alla Proprietà ".Cursor" di quegli Oggetti grafici, che la supportano, passando con il mouse sui quali, si desidera che l'aspetto del cursore muti.

Poniamo come esempio il caso in cui si vuole che l'aspetto del puntatore muti quando si passa con esso su una Label:

Private cu As Cursor


Public sub Form_Open()

 Dim pc As New Picture
 
' Viene caricata l'immagine da utilizzare per mutare l'aspetto del cursore del mouse:
 pc = pc.Load("/percorso/del/file/immagine")  
 
' Viene istanziata la variabile di tipo "Cursor":
 cu = New Cursor(pc)
    
' Viene assegnata la variabile di tipo "Cursor" alla Proprietà ".Cursor" della "Label", per attribuire la nuova immagine al puntatore, quando si passerà con esso sulla "Label":
 Label1.Cursor = cu

End

o più brevemente:

Public sub Form_Open()

 Dim pc As New Picture

 Label1.Cursor = New Cursor(pc.Load("/percorso/dell'immagine"))

End

Mutare l'aspetto del puntatore del mouse caricando un'immagine quando si entra nel Controllo grafico

Si potrà mutare l'aspetto del puntatore del mouse caricando un'immagine quando si entra nel Controllo grafico:

Public Sub Form_Enter()

 CreaPicture(Me.Name)

End

Public Sub TextArea1_Enter()

 CreaPicture(TextArea1.Name)

End

Public Sub TextBox1_Enter()

 CreaPicture(TextBox1.Name)

End

Private Procedure CreaPicture(nome As String)

 Dim pc As Picture
 
 pc = New Picture(100, 20, Color.SoftYellow, Image.Standard)
 With paint
   .Begin(pc)
   .DrawText(nome, 0, 0, pc.W, pc.H, Align.Normal)
   .End
 End With

 Last.Cursor = New Cursor(pc)
 
 pc.Clear

End

Utilizzare le icone fornite da Gambas

E' possibile anche utilizzare le icone fornite da Gambas:

Me.Cursor = New Cursor(Picture["icon:/16/erase"])

Ad ogni modo per far sapere al codice che si sta utilizzando una immagine del puntatore del Mouse mediante la Classe Cursor, si utilizzerà la Proprietà ".Custom" della Classe Mouse.

Public Sub Form_Open()

 Me.Cursor = New Cursor(Picture["icon:/16/erase"])

End

Public Sub Form_Enter()

 If Me.Mouse == Mouse.Custom Then Print Mouse.Custom

End


Modificare l'aspetto del cursore del mouse quando esso è all'esterno di qualsiasi finestra dell'applicazione Gambas

Quando il cursore del mouse è all'esterno di una qualsiasi finestra dell'applicazione Gambas, il suo aspetto può essere modificato mediante le funzioni esterne del API di X11.

In questo caso abbiamo due possibilità: impostare un aspetto scelto fra quelli indicati nel file header ".../X11/cursorfont.h" e visibili nella pagina "http://tronche.com/gui/x/xlib/appendix/b/", oppure un aspetto da noi liberamente disegnato.


Impostare un aspetto fra quelli indicati nel file header ".../X11/cursorfont.h"

Il file ".../X11/cursorfont.h" contiene 76 modelli di puntatori di mouse, a ciascuno dei quali è assegnato un numero (sempre di valore pari). E' possibile vedere quale aspetto tali modelli posseggono, accedendo ad esempio alla pagina WEB "http://tronche.com/gui/x/xlib/appendix/b/".

Il cambio dell'aspetto del puntatore del mouse deve sempre far riferimento ad una qualunque finestra presente sulla Scrivania (Desktop). Ciò vuol dire che la modifica del puntatore del mouse può avvenire solo se tale puntatore si trova all'interno della finestra prescelta dal programmatore. Sarà quindi necessario individuare il numero identificativo della finestra prescelta.

Mostriamo di seguito un esempio pratico, nel quale sarà possibile cambiare l'aspetto del puntatore del mouse solo se esso si trova direttamente al di sopra della Scrivania (Desktop). Se esso si troverà al di sopra della finestra di un programma, l'aspetto tornerà ad essere quello di default.

Come già detto, saranno utilizzate le funzioni esterne del API del sistema grafico X11.

Nell'apposito spazio sottostante la console, dopo aver avviato il progetto, si deve scrivere il numero che si riferisce al modello di cursore di mouse prescelto stando ovviamente con il cursore medesimo direttamente al di sopra del Desktop.
Se invece è stato creato l'eseguibile per farlo funzionare da Terminale, si dovrà nel Terminale scrivere il percorso dell'eseguibile seguito dal numero corrispondente al disegno di cursore prescelto, come visibile in "http://tronche.com/gui/x/xlib/appendix/b/". Esempio:

~ $ '/percorso/dell'/eseguibile.gambas' 14

Ad ogni modo, è sempre possibile cambiare aspetto del puntatore del mouse durante l'esecuzione dell'applicazione inviando da console, o da Terminale, un altro numero.

L'esempio che segue prevede che, qualora si intenda terminare l'esecuzione dell'applicazione, per tornare al classico aspetto predefinito del puntatore del mouse - quello di una freccia bianca che punta verso l'alto a sinistra - si dovrà, prima di terminare l'applicazione inviare il numero 2 . In caso di dimenticanza si potrà riavviare l'applicazione e così far tornare manualmente l'aspetto predefinito del puntatore del mouse, tenendo comunque presente che, ad ogni modo, la modifica del cursore dura per il solo durare della corrente sessione di sistema.

Va da sé, che anche durante l'esecuzione dell'esempio che segue, per ottenere nuovamente l'aspetto predefinito della freccia, si dovrà inviare il valore 2.

Private s As String


Library "libX11:6.4.0"

Private Const XA_CARDINAL As Integer = 6
Private Const XA_WINDOW As Integer = 33
Private Const MAX_PROPERTY_VALUE_LEN As Integer = 4096

' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display$ As String) As Pointer

' Window XDefaultRootWindow(Display *display)
' Return the root window for the default screen.
Private Extern XDefaultRootWindow(displayP As Pointer) As Integer

' Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists)
' Returns the atom identifier associated with the specified atom_name string.
Private Extern XInternAtom(displayP As Pointer, atom_name As String, only_if_exists As Boolean) As Integer

' int XGetWindowProperty(Display *display, Window w, Atom property, long long_offset, long long_length, Bool delete, Atom req_type, Atom *actual_type_return, int *actual_format_return, unsigned long *nitems_return, unsigned long *bytes_after_return, unsigned char **prop_return)
' Returns the actual type of the property; the actual format of the property.
Private Extern XGetWindowProperty(displayP As Pointer, wL As Long, py As Integer, lo As Long, ll As Long, d As Boolean, rt As Integer, at As Pointer, af As Pointer, ni As Pointer, ba As Pointer, pr As Pointer) As Integer

' Status XGetWMName(Display *display, Window w, XTextProperty *text_prop_return)
' Calls XGetTextProperty() to obtain the WM_NAME property.
Private Extern XGetWMName(displayP As Pointer, wL As Long, text_prop_return As Pointer) As Integer

' Cursor XCreateFontCursor(Display *display, unsigned int shape)
' Provides a set of standard cursor shapes in a special font named cursor.
Private Extern XCreateFontCursor(displayP As Pointer, shape As Integer) As Integer

' XDefineCursor(Display *display, Window w, Cursor cursor)
' If a cursor is set, it will be used when the pointer is in the window.
Private Extern XDefineCursor(displayP As Pointer, w As Long, cursorI As Integer) As Integer

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(displayP As Pointer)


Public Sub Main()

 Dim disp As Pointer
 Dim scrivania, crs As Integer
 
 s = Application.Args[1]
 If IsNull(s) Then s = "2"
  
' Connessione al server X ed impostazione di default:
 disp = XOpenDisplay(Null)
 If disp == 0 Then Error.Raise("Impossibile connettersi al Server X !")

 scrivania = IDScrivania(disp)

 Repeat
   Wait 0.01
   If IsNumber(s) Then
' Entrando il cursore del mouse nella finestra, esso cambia aspetto, impostando quello che nel file header "X11/cursorfont.h" ha il valore 2 tra quelli visibili nella pagina "http://tronche.com/gui/x/xlib/appendix/b/":
     crs = XCreateFontCursor(disp, Val(s))
     XDefineCursor(disp, scrivania, crs)
   Endif
   If s = "quit" Then
     crs = XCreateFontCursor(disp, 2)
     XDefineCursor(disp, scrivania, crs)
   Endif
 Until s = "quit"

' Chiude la libreria:
 XCloseDisplay(disp)
 Quit
 
End

Public Sub Application_Read()
 
 Input #File.In, s
 
End

Private Function IDScrivania(ds As Pointer) As Integer

 Dim datID, p As Pointer
 Dim x_num_Atom, tipo, formato As Integer
 Dim err, n_fin, bytes_succ, i As Integer
 Dim rootW As Long
 Dim stId As Stream
 Dim b As Byte
  
 rootW = XDefaultRootWindow(ds)
  
 x_num_Atom = XInternAtom(ds, "_NET_CLIENT_LIST", False)
  
 err = XGetWindowProperty(ds, rootW, x_num_Atom, 0, MAX_PROPERTY_VALUE_LEN / 4, False, XA_WINDOW, VarPtr(tipo), VarPtr(formato), VarPtr(n_fin), VarPtr(bytes_succ), VarPtr(datID))
 If err <> 0 Then Error.Raise("Impossibile ottenere dati dalla funzione 'XGetWindowProperty' !")
  
 If XA_WINDOW <> tipo Then Error.Raise("Tipo invalido di proprietà '_NET_CLIENT_LIST' !")
  
 p = Alloc(SizeOf(gb.Pointer), 4)

 stId = Memory datID For Read
  
 For b = 1 To n_fin * 2
   Read #stId, i
   If i > 0 Then
     XGetWMName(ds, i, p)
     If String@(Pointer@(p)) = "Scrivania" Then Exit
   Endif
 Next
 
' Va in chiusura:
 stId.Close
 Free(p)

 Return i
 
End


Impostare un aspetto da noi liberamente disegnato

Le risorse della libreria esterna X11 ci consentono di disegnare noi stessi un modello di puntatore per il mouse. Il disegno verrà impostato mediante l'inizializzazione di un apposito vettore.

Mostriamo un esempio pratico riprendendo ed integrando il precedente codice: nella finestra della Scrivania verrà disegnato un cursore a forma di matita con la punta rivolta in basso a destra definita da colori blu e giallo.
Dopo l'avvio può rendersi necessario attendere alcuni secondi prima che l'aspetto del mouse cambi.

Per tornare all'aspetto predefinito del puntatore del mouse, avere l'accortezza, prima di terminare l'applicazione, di inviare da Console o da Terminale il numero 2 !

Private s As String


Library "libX11:6.4.0"

Public Struct XColor
  pixel As Long
  red As Short
  green As Short
  blue As Short
  flags As Byte
 pad As Byte
End Struct

Private Const XA_CARDINAL As Integer = 6
Private Const XA_WINDOW As Integer = 33
Private Const MAX_PROPERTY_VALUE_LEN As Integer = 4096
 
' Display *XOpenDisplay(char *display_name)
' Opens a connection to the X server that controls a display.
Private Extern XOpenDisplay(display$ As String) As Pointer

' Screen *XDefaultScreenOfDisplay(Display *display)
' Returns a pointer to the default screen.
Private Extern XDefaultScreenOfDisplay(displayP As Pointer) As Pointer

' Window XDefaultRootWindow(Display *display)
' Return the root window for the default screen.
Private Extern XDefaultRootWindow(displayP As Pointer) As Integer

' Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists)
' Returns the atom identifier associated with the specified atom_name string.
Private Extern XInternAtom(displayP As Pointer, atom_name As String, only_if_exists As Boolean) As Integer

' int XGetWindowProperty(Display *display, Window w, Atom property, long long_offset, long long_length, Bool delete, Atom req_type, Atom *actual_type_return, int *actual_format_return, unsigned long *nitems_return, unsigned long *bytes_after_return, unsigned char **prop_return)
' Returns the actual type of the property; the actual format of the property.
Private Extern XGetWindowProperty(displayP As Pointer, wL As Long, py As Integer, lo As Long, ll As Long, d As Boolean, rt As Integer, at As Pointer, af As Pointer, ni As Pointer, ba As Pointer, pr As Pointer) As Integer

' Status XGetWMName(Display *display, Window w, XTextProperty *text_prop_return)
' Calls XGetTextProperty() to obtain the WM_NAME property.
Private Extern XGetWMName(displayP As Pointer, wL As Long, text_prop_return As Pointer) As Integer

' Pixmap XCreatePixmap(display *display, Drawable d, unsigned int width, unsigned int height, unsigned int depth)
' Creates a pixmap of the width, height, and depth you specified and returns a pixmap ID that identifies it.
Private Extern XCreatePixmap(displayP As Pointer, w As Long, width As Integer, height As Integer, depth As Integer) As Pointer

' Status XLookupColor(Display *display, Colormap colormap, char *color_name, XColor *exact_def_return, XColor *screen_def_return)
' Looks up the string name of a color with respect to the screen associated with the specified colormap.
Private Extern XLookupColor(displayP As Pointer, colormap As Pointer, color_name As String, exact_def_return As XColor, screen_def_return As XColor) As Integer

' Colormap XDefaultColormapOfScreen(Screen *screen)
' Returns the default colormap ID on the specified screen.
Private Extern XDefaultColormapOfScreen(XScreen As Pointer) As Pointer

' Pixmap XCreatePixmapFromBitmapData(display *display, Drawable d, char *data, unsigned int width, unsigned int height, unsigned long fg, unsigned long bg, unsigned int depth)
' Creates a pixmap of the given depth and then does a bitmap-format XPutImage() of the data into it.
Private Extern XCreatePixmapFromBitmapData(displayP As Pointer, w As Pointer, data As Byte[], width As Integer, height As Integer, fg As Long, bg As Long, depth As Integer) As Pointer

' Cursor XCreatePixmapCursor(Display *display, Pixmap source, Pixmap mask, XColor *foreground_color, XColor *background_color, unsigned int x, unsigned int y)
' Creates a cursor and returns the cursor ID associated with it.
Private Extern XCreatePixmapCursor(displayP As Pointer, source As Pointer, mask As Pointer, foreground_color As XColor, background_color As XColor, x As Integer, y As Integer) As Integer
 
' Cursor XCreateFontCursor(Display *display, unsigned int shape)
' Provides a set of standard cursor shapes in a special font named cursor.
Private Extern XCreateFontCursor(displayP As Pointer, shape As Integer) As Integer

' XDefineCursor(Display *display, Window w, Cursor cursor)
' If a cursor is set, it will be used when the pointer is in the window.
Private Extern XDefineCursor(displayP As Pointer, w As Long, cursorI As Integer) As Integer

' XCloseDisplay(Display *display)
' Closes the connection to the X server for the display specified in the Display structure and destroys all windows.
Private Extern XCloseDisplay(displayP As Pointer)


Public Sub Main()

 Dim disp, scr, pixmap, matita, matita_mask As Pointer
 Dim scrivania, cursor, cursore_matita As Integer
 Dim inut, cursore_primopiano, sfondo_cursore As New XColor
 Dim matita_bits As Byte[] = [&00, &70, &00, &88, &00, &8C, &00, &96, &00, &69, &80, &30, &40, &10, &20, &08,        ' Disegna il nuovo puntatore a forma di matita
                             &10, &04, &08, &02, &08, &01, &94, &00, &64, &00, &1E, &00, &06, &00, &00, &00]
 Dim matita_mask_bits As Byte[] = [&00, &F8, &00, &FC, &00, &FE, &00, &FF, &80, &FF, &C0, &7F, &E0, &3F, &F0,
                                  &1F, &F8, &0F, &FC, &07, &FC, &03, &FE, &01, &FE, &00, &7F, &00, &1F, &00, &07, &00]
 Dim matita_width As Integer = 16
 Dim matita_height As Integer = 16
 Dim matita_X As Integer = 1
 Dim matita_Y As Integer = 15
  
' Connessione al server X ed impostazione di default:
 disp = XOpenDisplay(Null)
 If disp == 0 Then Error.Raise("Impossibile connettersi al Server X !")

 scr = XDefaultScreenOfDisplay(disp)
 If scr == 0 Then Error.Raise("Errore !")
  
 scrivania = IDScrivania(disp)

' Crea le pixmap per il cursore del mouse:
 pixmap = XCreatePixmap(disp, XDefaultRootWindow(disp), 1, 1, 1)
 If pixmap == 0 Then Error.Raise("Errore !")

 XLookupColor(disp, XDefaultColormapOfScreen(scr), "yellow", inut, cursore_primopiano)
 XLookupColor(disp, XDefaultColormapOfScreen(scr), "blue", inut, sfondo_cursore)
 
 matita = XCreatePixmapFromBitmapData(disp, pixmap, matita_bits, matita_width, matita_height, 1, 0, 1)
 If matita == 0 Then Error.Raise("Errore !")
 matita_mask = XCreatePixmapFromBitmapData(disp, pixmap, matita_mask_bits, matita_width, matita_height, 1, 0, 1)
 If matita_mask == 0 Then Error.Raise("Errore !")
 cursore_matita = XCreatePixmapCursor(disp, matita, matita_mask, cursore_primopiano, sfondo_cursore, matita_X, matita_Y)
  
 Repeat
   Wait 0.01
   If IsNumber(s) Then
' E' possibile, inviando da Console o da Terminale il numero "2", far tornare l'aspetto predefinito del puntatore; oppure impostare un altro aspetto tra queli previsti nella pagina "http://tronche.com/gui/x/xlib/appendix/b/":
     crs = XCreateFontCursor(disp, Val(s))
     XDefineCursor(disp, scrivania, crs)
   Else 
' Entrando il cursore del mouse nella finestra, esso cambia aspetto, come da noi disegnato:
   XDefineCursor(disp, scrivania, cursore_matita)
   Endif
   If s = "quit" Then
     cursor = XCreateFontCursor(disp, 2)
     XDefineCursor(disp, scrivania, cursor)
   Endif
 Until s = "quit"
 
' Chiude la libreria:
 XCloseDisplay(disp)
 Quit
 
End

Public Sub Application_Read()

 Input #File.In, s

End

Private Function IDScrivania(ds As Pointer) As Integer

 Dim datID, p As Pointer
 Dim x_num_Atom, tipo, formato As Integer
 Dim err, n_fin, bytes_succ, i As Integer
 Dim rootW As Long
 Dim stId As Stream
 Dim b As Byte
  
 rootW = XDefaultRootWindow(ds)
  
 x_num_Atom = XInternAtom(ds, "_NET_CLIENT_LIST", False)
  
 err = XGetWindowProperty(ds, rootW, x_num_Atom, 0, MAX_PROPERTY_VALUE_LEN / 4, False, XA_WINDOW, VarPtr(tipo), VarPtr(formato), VarPtr(n_fin), VarPtr(bytes_succ), VarPtr(datID))
 If err <> 0 Then Error.Raise("Impossibile ottenere dati dalla funzione 'XGetWindowProperty' !")
  
 If XA_WINDOW <> tipo Then Error.Raise("Tipo invalido di proprietà '_NET_CLIENT_LIST' !")
  
 p = Alloc(SizeOf(gb.Pointer), 4)

 stId = Memory datID For Read
  
 For b = 1 To n_fin * 2
   Read #stId, i
   If i > 0 Then
     XGetWMName(ds, i, p)
     If String@(Pointer@(p)) = "Scrivania" Then Exit
   Endif
  Next
 
' Va in chiusura:
 stId.Close
 Free(p)

 Return i
 
End