Difference between revisions of "Extensions development basic fr"

From Apache OpenOffice Wiki
Jump to: navigation, search
(Desktop, documents, et current selection)
(Introspection)
Line 240: Line 240:
  
 
==Introspection==
 
==Introspection==
HasUnoInterfaces is an OpenOffice.org Basic function for introspection. See this [[http://www.oooforum.org/forum/viewtopic.phtml?t=7068 link]] for information on introspection in other languages.  
+
HasUnoInterfaces est une fonction OpenOffice.org Basic utilisée pour l'introspection. Ce document  [[http://www.oooforum.org/forum/viewtopic.phtml?t=7068 link]] permettra d'apprendre ce que l'on entend par introspection dans d'autres langages de programmation.  
  
HasUnoInterfaces returns true if all of the specified interfaces are available for the specified object.  
+
HasUnoInterfaces renvoie une valeur "vrai" si toutes les interfaces spécifiées sont disponibles pour l'objet appelant.  
  
Most OpenOffice.org objects provide the method supportsService because they have the interface com.sun.star.lang.XServiceInfo.  
+
La plupart des objets OpenOffice.org fournissent la méthode supportsService parce qu'ils disposent également de l'interface com.sun.star.lang.XServiceInfo.  
  
In the above example, the OpenOffice.org Basic command, '''HasUnoInterfaces''' checks that the current document has the interface com.sun.star.lang.XServiceInfo, because if it doesn't have that interface then it doesn't have the method supportsService, and a run time error would occur if such an object tried to access its nonexistent method.
+
Dans l'exemple ci-dessus, la commande OpenOffice.org Basic, '''HasUnoInterfaces''' vérifie si le document actif dispose de l'interface com.sun.star.lang.XServiceInfo, car si cette interface n'est pas présente, alors le document n'aura pas non plus la méthode supportsService, et une erreur d'exécution se produirait lorsqu'un objet tentait d'accéder à une méthode inexistante.  
 
+
'''SupportsService''' is a method which returns true if the specified service is available. The above examples checks for a service to determine the type of document that is currently active.
+
  
 +
'''SupportsService''' est une méthode qui renvoie la valeur "vrai" si le service spécifié est disponible. Dans l'exemple ci-dessus, on vérifie la présence d'un service afin de déterminer le type de document en cours d'activation.
  
 
==L'Outil X-Ray==
 
==L'Outil X-Ray==

Revision as of 13:00, 13 October 2006

Comment démarrer

Cette page est un guide de démarrage qui vous permettra d'écrire des macros en OpenOffice.org Basic. Une connaisance préalable de la programmation est un pré-requis. Merci d'éditer cette page pour la rendre plus lisible. J'espère que vous la trouverez utile.

Si vous maîtrisez les bases, alors vous pouvez consulter le CookBook qui donne des exemples et des (wrappers).


Où le code est-il enregistré ?

Le code OpenOffice.org Basic est enregistré dans des modules eux-mêmes placés dans les bibliothèques. Une bibliothèque peut être :

  • Partagée (pour une installation en réseau - OOo Macros & Dialogues)
  • Uniquement pour l'utilisateur courant (Mes Macros & Dialogues)
  • Incorporée à un document ou à un modèle de telle manière que son code ne soit disponible que lorsque ce document est ouvert.

Lorsque des bibliothèques ne sont stockées ni dans un document ni dans un modèle, c'est-à-dire lorsque les bibliothèques sont partagées ou pour l'utilisateur courant, on les appelle Bibliothèques OpenOffice.org.

Pour connaître les dossiers qui contiennent les bibliothèques OpenOffice.org voir :
Outils > Options… > OpenOffice.org > Chemins > BASIC.

Note Ne copiez pas ni ne déplacez les bibliothèques en utilisant les commandes du système d'exploitation. Préférez le gestionnaire de macros ou le gestionnaire de packages.


La taille autorisée pour les modules placés à l'intérieur des bibliothèques est limitée à 64 Ko. Une bilbiothèque peut contenir jusqu'à 16.000 modules.

Pour plus d'information, reportez-vous à l'aide en ligne, rubrique : Modules et bibliothèques.

Accéder à l'IDE

Pour accéder à l'IDE (environnement de développement intégré) pour la première fois :

OpenOffice.org 1.1.x: Outils > Macros > Macro… >

OpenOffice.org 1.9.x et ultérieur : Outils > Macros > Gérer les macros > OpenOffice.org Basic… >

Pour commencer, nous allons utiliser le Module1 de la bibliothèque Standard, présente pour l'utilisateur courant uniquement :

Entrons un nom pour notre nouvelle macro : HelloWorld

Dans la macro, sélectionnons Standard dans la boîte de liste.

Cliquons Nouveau

Nous devons maintenant trouver quelque chose comme çà :

[oobas] REM ***** BASIC *****

Sub Main

End Sub

Sub HelloWorld

End Sub Le curseur est positionné au début de la ligne Sub HelloWorld.

Note Maintenant que l'IDE est actif, il peut être accédé depuis le menu Fenêtre d'OpenOffice.org ou par la barre des tâches du système d'exploitation.

Saisie de code

Selectionnons et effaçons :

[oobas] REM ***** BASIC *****

Sub Main

End Sub Au-dessous de la ligne "Sub HelloWorld" entrons msgbox "Hello World!", de manière que l'éditeur ressemble à ceci :

[oobas] Sub HelloWorld

 msgbox "Hello World!"

End Sub

Notes: L'IDE ne fournit aucune fonctionnalité de code completion ni d'aide sur la syntaxe des commandes lors de la frappe. Pour obtenir de l'aide sur une commande Basic, plaçons le curseur dans la commande et tapons F1.
Les commande OpenOffice.org Basic ne sont pas sensibles à la casse. C'est pourquoi msgbox, MSGBOX et Msgbox sont équivalents.
Les chaînes sont entourées de guillements doubles.

Exécution du code

Le code Basic peut être exécuté de plusieurs façons :

Directement dans l'IDE. La barre des macro comprte un bouton Exécter (par défaut, le troisième de la seconde barre d'outils). Ce bouton lance la première macro du module en cours.

Depuis le menu Outils :

(Version 1.1.x) Outils > Macros > Macro…;

(Version 1.9.x et supérieures) Outils > Macros > Exécuter la macro…

Par assignation de la macro à une touche.

Par assignation de la macro à une entrée de menu.

Par assignation de la macro à un bouton de barre d'outil.

En créant un contrôle dans un document.

Par assignation de la macro à un évènement.

Pour l'instant essayons de lancer la procédure "HelloWorld" en cliquant le bouton Exécuter. Un dialogue intitulé "soffice" et comportant le texte "Hello World!" ainsi qu'un bouton OK doit s'afficher.

Enregistrement du code

Le code est enregistré automatiquement chaque fois que son conteneur est lui-même enregistré. Par conséquent, si le code se trouve dans une bibliothèque OpenOffice (partagée ou de l'utilisateur), il est automatiquement enregistré lorsque OpenOffice est refermé. Si le code se trouve dans une bilbiothèque qui fait partie d'un document, alors il est enregistré lorsque le document l'est.

Un bouton Enregistrer figure sur la barre d'outils Standard (celle du haut par défaut). Si le code se trouve à l'intérieur d'un document ou modèle, alors la totalité du document est enregistrée. Si le code se trouve à l'intérieur d'une bibliothèque OpenOffice.org alors seule la bilbiothèque courante est enregistrée.

Les variables

Nous pouvons forcer la déclaration des variables en insérant Option Explicit au début du module. Pour consulter une discussion consacrée à la déclaration ou non des variables, voir : [cette discussion].

Dans cette discussion, on voit que l'auteur de [NdT : la version anglaise de] cette page défendait initialement la déclaration systématique des variables. Depuis lors il a changé d'avis et ne les déclare plus du tout. Bref, c'est une question de préférence personnelle. Dans un cas comme dans l'autre, les préférences de l'auteur vont au nommage des variables selon la convention suivante, qui sera utilisée tout au long des exemples de ce wiki :

La première lettre du nom de la variable indique le type de valeur contenue, telle que présentée à la table ci-dessous (basée sur un tableau dans Tutorial.pdf de Sun)

Lettre Signification
a Structure
b Boolean (TRUE ou FALSE)
e Enumeration. Cette variable ne peut prendre qu'une valeur parmi un ensemble limité de valeurs.
f Float (de 3.402823 x 1038 à 1.401298 x 10-45. Une variable de type float [NdT : single] peut occuper jusqu'à quatre octets)
Double (de 1.79769313486232 x 10308 à 4.94065645841247 x 10-324. Une variable de ce type peut occuper jusqu'à huit octets)
Currency (de -922337203685477.5808 à +922337203685477.5807 et occupe jusqu'à huit octets en mémoire)
m Array (aka sequence aka matrice)
n Integer (de -32768 à 32767.) ou
Long (de -2147483648 à 2147483647).
o Object, service ou interface
s String (Une variable string peut mémoriser jusqu'à 65535 caractères Unicode).
x Interface, montre que seules les opérations portant sur une interface particulière d'un objet sont utilisées
v Variant, N'importe quel valeur


Utilisons des noms descriptifs suffisamment longs et employons le style "Camel case" [NdT : usage conjoint des majuscules et des minuscules pour faire ressortir les éléments du nom]

Note : Les variables définies par l'utilisateur en OpenOffice.org Basic ne sont pas sensibles à la casse. Les constantes UNO-API le sont.


Les variables indexant les boucles constituent une exception conventionnelle aux longs noms descriptifs. Des symboles tels que i, j et k sont en effet d'usage fréquent. De même, lorsqu'une chaîne est construite, on utilise fréquemment s comme variable temporaire.

Editons la routine sub HelloWorld de manière qu'elle ressemble à ceci et exécutons-la :

[oobas] sub HelloWorld dim i as integer 'ligne optionnelle

 for i = 0 to 2
   'Ces lignes sont indentées par souci de lisiblité uniquement
   'Notre code devrait toujours être structuré ainsi pour lui donner des chances de survie
   msgbox "Hello World " & i
 next i

end sub Pour plus d'informations sur les variables, reportons-nous à l'aide en ligne, rubrique "utilisation des variables".

L'API OpenOffice.org

Cette section commence par un exemple. La suite donne des informations complémentaires qui nous permettront de comprendre l'exemple et à l'étendre.

Essayons d'exécuter le code ci-dessous lorsque différents types de documents sont ouverts.

[oobas] sub main 'basicLibraries.loadLibrary("Xray") 'xray.xray thisComponent msgbox fnWhichComponent(thisComponent) end sub


function fnWhichComponent(oDoc) as string if HasUnoInterfaces(oDoc, "com.sun.star.lang.XServiceInfo") then

  if thisComponent.supportsService ("com.sun.star.text.GenericTextDocument") then
     fnWhichComponent = "Texte"
  elseif thisComponent.supportsService("com.sun.star.sheet.SpreadsheetDocument") then
     fnWhichComponent = "Feuille de calcul"
  elseif thisComponent.supportsService("com.sun.star.presentation.PresentationDocument") then
     fnWhichComponent = "Presentation"
  elseif thisComponent.supportsService("com.sun.star.drawing.GenericDrawingDocument") then
     fnWhichComponent = "Dessin"
  else
     fnWhichComponent = "Oops le document ouvert est autre chose"
  end if

else

  fnWhichComponent = "Ce n'est pas un document"

end if End function

Convention de nommage des routines

Dans l'exemple ci-dessus, le nom de la fonction utilisateur commence par "fn". Il s'agit de la convention adoptée par l'auteur initial [NdT : version anglaise] qui permet au lecteur de savoir qu'il s'agit d'une fonction définie par l'utilisateur. Dans le même esprit, l'auteur initial utilise la convention de débuter les noms des procédures par "sub". Lorsque l'on apprend un nouveau langage et de nouvelles API, il peut s'avérer difficile de reconnaître ce qui ressortit du langage lui-même de ce qui a été défini ailleurs dans notre code. Ce document/wiki emploie ces conventions pour le nommage des fonctions et des procédures.

Présentation de l'API OpenOffice.org

Cette section introduit les termes :

  • Interface
  • Module
  • Service
  • Méthode
  • Propriété

S'il n'est pas essentiel de comprendre la différence entre une interface et un service ou ce qu'est un module pour pouvoir écrire des extensions à OpenOffice.org, la compréhension de ces termes aide à correctement interpréter la documentation ainsi qu'à l'introspection des éléments manipulés. Peut-être nous faudra-t-il relire cette section plusieurs fois.

Une interface est la définition d'un ensemble de méthodes (avec leurs arguments) qu'un service implémentant cette interface doit comporter.

Les interfaces sont regroupées en modules pour des besoins de nommage. Toutes les interfaces (et les services) commencent par le nom "com.sun.star" puis vient le nom du module puis celui de l'interface (ou du service).

Par exemple, la plupart des services fournissent l'interface com.sun.star.beans.XPropertySet. Cette interface est enregistrée dans le module "beans" et fournit l'accès aux propriétés d'un service. Une propriété est une valeur tandis qu'une méthode défiti une action.

Un objet OpenOffice.org peut supporter de nombreux services.

Un objet OpenOffice.org peut supporter un service qui implémente une interface dans laquell une description de méthode déclare qu'un autre objet OpenOffice.org est retourné.

Introspection

HasUnoInterfaces est une fonction OpenOffice.org Basic utilisée pour l'introspection. Ce document [link] permettra d'apprendre ce que l'on entend par introspection dans d'autres langages de programmation.

HasUnoInterfaces renvoie une valeur "vrai" si toutes les interfaces spécifiées sont disponibles pour l'objet appelant.

La plupart des objets OpenOffice.org fournissent la méthode supportsService parce qu'ils disposent également de l'interface com.sun.star.lang.XServiceInfo.

Dans l'exemple ci-dessus, la commande OpenOffice.org Basic, HasUnoInterfaces vérifie si le document actif dispose de l'interface com.sun.star.lang.XServiceInfo, car si cette interface n'est pas présente, alors le document n'aura pas non plus la méthode supportsService, et une erreur d'exécution se produirait lorsqu'un objet tentait d'accéder à une méthode inexistante.

SupportsService est une méthode qui renvoie la valeur "vrai" si le service spécifié est disponible. Dans l'exemple ci-dessus, on vérifie la présence d'un service afin de déterminer le type de document en cours d'activation.

L'Outil X-Ray

L'utilisation de "HasUnoInterfaces" et de "supportsService" permet d'obtenir des informations sur un objet donné lors de son exécution, mais procéder ainsi pour apprendre le langage Basic deviendrait vite fastidieux. Heureusement, et grâce à Bernard Marcelly, nous disposons de l'outil X-Ray. Cet outil est disponible ici: [ooomacros]. Téléchargez le fichier zip, dézippez l'archive, ouvrez le document dans OpenOffice.org, et suivez les instructions pour son installation et configuration.

Une partie de la configuration de l'outil X-Ray concerne la définition de l'endroit où est stockée une copie locale (sur le disque dur) du Kit de Développement OpenOffice.org (appélé SDK). Téléchargez le Kit de Développement OpenOffice.org depuis [[1]] et installez le sur votre disque dur.

Dans l'exemple ci-dessus, au début du code, il y a deux lignes mises en commentaires (les lignes de commentaires commencent toujours avec des apostrophes):

[oobas] 'basicLibraries.loadLibrary("Xray") 'xray.xray thisComponent Une fois l'outil X-Ray installé, supprimez les apostrophes dans les lignes indiquées ci-dessus et relancez la macro. A partir de la version 5, la commande à utiliser dans votre code est tout simplement "xray".

BasicLibraries est une commande OpenOffice.org Basic qui renvoie un objet permettant d'accéder aux bibliothèques OpenOffice.org. La méthode loadLibrary rend disponible aux utilisateurs les routines présentes dans cette bibliothèque.

xray.xray indique la bibliothèque xray et la sous-routine xray contenue dans celle-ci, l'objet thisComponent étant l'objet transmis à xray pour l'introspection.

Afin de trouver l'objet que vous cherchez, il est souvent nécessaire de le découvrir ou de le créer depuis StarDesktop ou thisComponent.

Desktop, documents, and current selection

StarDesktop et ThisComponent sont des commandes OpenOffice.org Basic qui ont trait à l'application et le document actif (c'est-à-dire, celui qui a le focus actuellement sur le bureau) respectivement.

Contrairement à Microsoft Office, l'application OpenOffice.org est monolithique et comporte différents composants. Lorsqu'on exécute du code, il peut être utile de vérifier quel composant est actuellement en cours d'activation. Le code ci-dessus donne un exemple de la manière de procéder à cette vérification.

Quand il est fait référence au Desktop dans StarDesktop, celui-ci se réfère à une existence virtuelle (puisqu'auparavant il existait réellement dans OpenOffice.org et dans StarOffice). On peut ainsi le considérer comme étant l'application OpenOffice.org elle-même.

Creating new documents

To create a new text document:

[oobas] oDoc = StarDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, Array()) To create a new spreadsheet document:

[oobas] oDoc = StarDesktop.loadComponentFromURL("private:factory/scalc", "_blank", 0, Array()) An easier approach would be to write a simple function:

[oobas] function fnNewDoc(sDocType as string) fnNewDoc = StarDesktop.loadComponentFromURL("private:factory/" & sDocType , "_blank", 0, Array()) end function Then creating new documents can be achieved with:

[oobas] oDoc = fnNewDoc("swriter") oDoc = fnNewDoc("scalc") oDoc = fnNewDoc("simpress") oDoc = fnNewDoc("sdraw") oDoc = fnNewDoc("smath") See http://api.openoffice.org/docs/common/ref/com/sun/star/frame/XComponentLoader.html .

To open a document

The following example shows how to open a file. For information on URLs in OpenOffice.org see URL Basics.

[oobas] sFile = "C:\Documents and Settings\danny\Desktop\MyCalc.sxc" ' Windows sFile = "/home/danny/Desktop/MyCalc.sxc" ' Linux sURL = ConvertToURL(sFile) oDoc = StarDesktop.loadComponentFromURL(sURL, "_blank", 0, Array()) Again it may make sense to make this easier by writing a simple function:

[oobas] function fnOpenDoc(sFile) sURL = ConvertToURL(sFile) fnOpenDoc = StarDesktop.loadComponentFromURL(sURL, "_blank", 0, Array()) end function Examples of calling the function:

[oobas] oDoc = fnOpenDoc("C:\Documents and Settings\danny\Desktop\MyCalc.sxc") ' Windows oDoc = fnOpenDoc("/home/danny/Desktop/MyCalc.sxc") ' Linux

Current Selection

It is common to want to run some code that effects the current selection. ThisComponent has the method getCurrentSelection. Since many different types of objects could possibly be selected it is common to check that the currently selected object has the service that contains the method that we want to apply to the object.

Edit the main subroutine to the following and rerun it on a text document with different selections. (To select more than one block of text hold down the control key).

[oobas] sub main basicLibraries.loadLibrary("Xray") if fnWhichComponent(thisComponent) = "Text" then

       oCurSelection = thisComponent.getCurrentSelection()
       'xray.xray oCurSelection
       if oCurSelection.supportsService("com.sun.star.text.TextRanges") then
               msgbox "There are " & oCurSelection.getCount() & _
                " selections in the current text document."
       end if

end if end sub With nothing selected the number of selections is one - the insertion point, with one block of text selected the count is still one, but with two blocks of text the count is three - the insertion point and the two blocks of selected text.

Exercise 1: Modify the above code so that it works on selected cell ranges in a spreadsheet.

Question1: For two blocks of cells selected, what would be the count for the number of selections?


Properties

Uncomment 'xray.xray oCurSelection so that xray runs, to see that the object that oCurSelection points to has a "property" called Count with a description of "pseudo-prop, read only". It is possible in OpenOffice.org Basic to write oCurSelection.count, but as this is not possible in all other languages accessing the OpenOffice.org API, this Wiki will try to always use the method approach. (I say try because I have not been in the habit of doing this and sometimes I may forget).

This next example demonstrates changing a property value for the current selections.

[oobas] sub main basicLibraries.loadLibrary("Xray") if fnWhichComponent(thisComponent) = "Text" then

  oCurSelection = thisComponent.getCurrentSelection()
  if oCurSelection.supportsService("com.sun.star.text.TextRanges") then
     nCount = oCurSelection.Count
     'xray.xray oCurSelection.getByIndex(0)
     'Warning: The insertion point will have the same action applied twice
     'in this case it doesn't matter, but in others it might.
     for i = 0 to nCount - 1
        oCurSelection.getByIndex(i).setPropertyValue("CharStyleName", "Strong Emphasis")
     next
  end if

end if end sub In OpenOffice.org Basic it is possible to shorten the assignment line to:

[oobas] oCurSelection(i).CharStyleName = "Strong Emphasis" This wiki will try to use the full methods for both indexing and assigning properties. The rationale is that this makes converting the code to other languages easier and also helps the learner to understand what is happening (again I have not been in the habit of doing this so some examples may slip past me).

Exercise 2: Rewrite the above code so that the warning can be removed.

See Current selection.

Iterative Access to Subordinate Objects (Enumeration access)

Sometimes to access the desired object an enumeration is required. For example paragraphs, within a document or within a selection.

When a Writer document is active and some text is selected, both thisDocument.getText() and thisComponent.getCurrentSelection().getByIndex(i) have the service: com.sun.star.text.TextRange which has the interface: com.sun.star.container.XContentEnumerationAccess, it is possible to create an enumeration of the paragraphs for the current document or for a particular selection.

[oobas] ' Create enumeration object oTextElementEnum = thisComponent.getText().createEnumeration() 'or thisComponent.getCurrentSelection().getByIndex(i).createEnumeration()

' loop over all text elements while oTextElementEnum.hasMoreElements()

       oTextElement = oTextElementEnum.nextElement
       if oTextElement.supportsService("com.sun.star.text.TextTable") then
               MsgBox "The current block contains a table."
       end if
       if oTextElement.supportsService("com.sun.star.text.Paragraph") then
               MsgBox "The current block contains a paragraph."
       end if

wend Exercise 3: Extend the above example to display in a message box all text portions that are bold.


Named access

Some objects provide named access to a particular type of subordinate object, some others indexed access, and some both named and indexed access.

For example if the current document in OpenOffice.org is a spreadsheet then to access a particular sheet can be done by index access:

[oobas] oSheet = thisComponent.getSheets.getByIndex(0) or named access:

[oobas] oSheet = thisComponent.getSheets.getByName("Sheet1") To check if an object with a particular name already exists use hasByName, for example:

[oobas] if thisComponent.getSheets.hasByName("Sheet1") then To loop through all the available object names can be done like:

[oobas] mNames = thisComponent.getSheets.getElementnames for i = lbound(mNames) to ubound(mNames)

       msgbox mNames(i)

next


Some named subordinate objects also provide the interface: com.sun.star.container.XNameContainer. This interface defines that such objects should have the following methods: insertByName, replaceByname and removeByName.

E.g.

[oobas] thisComponent.getSheets.insertByName("NewSheet")

Create new objects

Some objects have services which implement interfaces to provide specific methods for creating a particular type of object.

For example if the current document is a Writer document then thisComponent.getText is an object that provides the service com.sun.star.text.Text which implements the interface com.sun.star.text.XSimpleText which defines the methods createTextCursor and createTextCursorByRange. Both of these methods create a text cursor for accessing the text of the document. These cursors are quite independent of the view cursor . The view cursor is visible on the screen and is manipulated by the user (and can be manipulated by program control), where as a text cursor is not visible on the screen and is solely used by program control. The following code snippet demonstrates creating a new text cursor, such that it starts at the same location as the viewCursor and is then moved independent of the view cursor.

[oobas] oVC = thisComponent.getCurrentController.getViewCursor oCursor = oVC.getText.createTextCursorByRange(oVC) oCursor.gotoStartOfSentence(false) oCursor.gotoEndOfSentence(true) msgbox oCursor.getString

Some objects are context dependent and get created using the method createInstance which is defined in the interface com.sun.star.lang.XMultiServiceFactory. For example to add a rectangle to the first page of a drawing document:

[oobas] dim aPoint as new com.sun.star.awt.Point dim aSize as new com.sun.star.awt.Size

aPoint.x = 1000 aPoint.y = 1000

aSize.Width = 10000 aSize.Height = 10000

oRectangleShape = thisComponent.createInstance("com.sun.star.drawing.RectangleShape") oRectangleShape.Size = aSize oRectangleShape.Position = aPoint

thisComponent.getDrawPages.getByIndex(0).add(oRectangleShape)

This example also uses UNO structs see below for more information on UNO stucts.

Some objects are context independent to create these objects use the OpenOffice.org Basic command createUnoService. For example to create the equivalent to StarDesktop:

[oobas] oDesktop = createUnoService("com.sun.star.frame.Desktop")

The process that I use to determine how to access or create an object is as follows:

Does the object already exist if so I should be able to access it from something like thisComponent.

Will the new object belong to another object, if so does the owner have a specific method for creating the object, if so use it.

The new object will belong to another object, but that object doesn't provide a specific method for creating it, but does provide createInstance. If the object doesn't provide createInstance are you sure you are using the correct object, or is it context independent.

I have found working out how to create an object to be quite difficult with existing documentation so I hope that this document/wiki will eventually make this clear.


UNO structs

UNO structures can be declared using the OpenOffice.org Basic command dim:

[oobas] dim aPoint as new com.sun.star.awt.Point Or by using the OpenOffice.org Basic command createUnoStruct:

[oobas] aPoint = createUnoStruct("com.sun.star.awt.Point")

Note: When declaring UNO structs case is important. Note that everything upto the name of the struct is lowercase, and that the name of the struct is in TitleCase.



Creating Listeners and Handlers

Through the user interface it is possible to assign macros to some events:

OpenOffice.org versions 1.1.x: Tools > Configure… > Events.

OpenOffice.org versions 1.9.x and above: Tools > Customize… > Events.

It is also possible to assign macros to a wider range of events using the OpenOffice.org Basic command CreateUnoListener. This same command is used for creating both listeners and handlers. A listener checks for an event and always allows other listeners to respond to the event as well. A handler listens for an event, and can optionally consume the event so that other listeners don't get to act on it.

The following example creates a keyHandler:

[oobas] global IannzExampleKeyHandler

sub SetupKeyHandler oController = thisComponent.currentController IannzExampleKeyHandler = CreateUnoListener("KeyHandler_","com.sun.star.awt.XKeyHandler") oController.addKeyHandler(IannzExampleKeyHandler) ' Register the listener end sub


sub RemoveKeyHandler thisComponent.currentController.removeKeyHandler(IannzExampleKeyHandler) end sub


sub KeyHandler_disposing end sub


function KeyHandler_keyReleased(oKeyEvent as new com.sun.star.awt.KeyHandler) as boolean

       KeyHandler_keyReleased = False    

end function


function KeyHandler_keyPressed(oKeyEvent as new com.sun.star.awt.KeyHandler) as boolean KeyHandler_keyPressed = false 'Let other listeners handle the event if oKeyEvent.modifiers = com.sun.star.awt.KeyModifier.MOD2 then 'Control key was pressed

       if oKeyEvent.keyCode = com.sun.star.awt.Key.Q then
               msgbox "Alt + Q was pressed"
               KeyHandler_keyPressed = true    'Don't let other listeners process this event
       end if

end if end function A variable declared as global keeps its value even after the macro exits. In this case we want to be able to use this variable later to remove the handler. As variables declared globally could be used in other libraries to try and avoid conflict I start all my global variables with Iannz my registered name for the OpenOffice.org web site.

sub SetupKeyHandler sets up the handler. The first parameter to CreateUnoListener is the staring name for the methods that will be called when that type of event occurs in this example ."KeyHandler_".

The second parameter is the name of the interface for the listener or handler, "com.sun.star.awt.XKeyHandler". The name is case sensitive, everything up to and including the module name is always lowercase, the name of the interface always starts with "X" and the remainder is in TitleCase.

Use the SDK to find out what methods the interface must supply. You must supply routines for all of these methods even if you don't intend to use them. You also need to supply a disposing method. The names of these routines start with the string given in the first parameter to CreateUnoListener , in this example "KeyHandler_".

Thus in the example there is KeyHandler_disposing and KeyHandler_keyReleased which don't actually do anything but are required, and KeyHandler_keyPressed which actually does the job.

sub RemoveKeyHandler demonstrates how to remove the handler.

OpenOffice.org constants

The above example uses OpenOffice.org constants.

E.g. com.sun.star.awt.KeyModifier.MOD2

OpenOffice.org constants are case sensitive. Everything up to and including the module name is always lowercase. The constant group is in TitleCase. The actual constant name is always UPPERCASE.

Programmers not using OpenOffice.org Basic may not have access to these constants.


Using the recorder

See The OpenOffice.org recorder and UNO dispatch calls section for a discussion on recording UNO Dispatch commands versus writing API calls.

See also

Personal tools