Difference between revisions of "DE/Makro Basic Tutorial"

From Apache OpenOffice Wiki
< DE
Jump to: navigation, search
m (Introspektion: translation continued)
m (Introspektion: minor changes)
Line 259: Line 259:
 
== Introspektion ==
 
== Introspektion ==
  
HasUnoInterfaces ist eine OpenOffice.org-Basic-Funktion zur Introspektion. Informieren Sie sich über  [[http://www.oooforum.org/forum/viewtopic.phtml?t=7068 Introspektion in anderen Sprachen]].
+
'''HasUnoInterfaces''' ist eine OpenOffice.org-Basic-Funktion zur Introspektion. Informieren Sie sich über  [[http://www.oooforum.org/forum/viewtopic.phtml?t=7068 Introspektion in anderen Sprachen]].
  
HasUnoInterfaces gibt "true" zurück wenn beim spezifizierten Objekt alle spezifizierten Schnittstellen verfügbar sind.
+
HasUnoInterfaces gibt <code>true</code> zurück wenn beim spezifizierten Objekt alle spezifizierten Schnittstellen verfügbar sind.
  
Die meisten OpenOffice.org-Objekte enthalten die Methode supportsService weil sie die Schnittstelle com.sun.star.lang.XServiceInfo haben.
+
Die meisten OpenOffice.org-Objekte enthalten die Methode '''supportsService''' weil sie die Schnittstelle <code>com.sun.star.lang.XServiceInfo</code> enthalten.
  
Im obigen Beispiel prüft '''HasUnoInterfaces''', ob das aktuelle Dokument die Schnittstelle com.sun.star.lang.XServiceInfo implementiert, da andernfalls die Methode supportsService fehlen würde. Der Aufruf dieser Methode würde in diesem Fall einen Laufzeitfehler verursachen.
+
Im obigen Beispiel prüft HasUnoInterfaces, ob das aktuelle Dokument die Schnittstelle <code>com.sun.star.lang.XServiceInfo</code> implementiert, da andernfalls die Methode supportsService fehlen würde. Der Aufruf dieser Methode würde in diesem Fall einen Laufzeitfehler verursachen.
  
'''supportsService''' ist eine Methode, die den Wert true zurückgibt, wenn der spezifizierte Service verfügbar ist. Das obige Beispiel prüft das Vorhandensein eines Service, um so den Typ des aktuell aktiven Dokuments zu bestimmen.
+
'''supportsService''' ist eine Methode, die den Wert <code>true</code> zurückgibt, wenn der spezifizierte Service verfügbar ist. Das obige Beispiel prüft das Vorhandensein eines Service, um so den Typ des aktuell aktiven Dokuments zu bestimmen.
  
 
==X-Ray tool==
 
==X-Ray tool==

Revision as of 18:57, 5 May 2006


Achtung, work in progress

Dieses Dokument wird gerade übersetzt, wer mag, darf auch gerne helfen.

Arbeitstitel: "Einführung: Basic für OOo-Erweiterungen"
Originaldokument: Extensions_development_basic
Ursprünglicher Autor: Ian Laurenson
offene Fragen: sind mit ??? gekennzeichnet

Diese Seite soll Ihnen eine Einführung in das Schreiben von Makros mit OpenOffice.org Basic geben. Grundkenntnisse im Programmieren werden vorausgesetzt. Bitte fühlen Sie sich frei, diese Seite zu editieren, um sie lesbarer zu machen. Ich hoffe, das Sie Ihnen von Nutzen sein wird.

Wenn Sie bereits mit den Grundlagen vertraut sind, können Sie sich auch direkt im KochBuch (CookBook) Wrapper (Hüllfunktionen ???) und Beispiele anschauen.


Wohin schreibe ich den Code?

Der Basic-Code wird bei OpenOffice.org in Modulen gespeichert, die in Bibliotheken zusammengefasst sind.

Eine Bibliothek kann

  • allgemein, also für die gesamte (Netzwerk-) Installation verfügbar sein ("OOo Makros und Dialoge")
  • nur für den aktuellen Benutzer verfübar sein ("Meine Makros und Dialoge")
  • in einem Dokument oder in einer Vorlage abgelegt sein, so dass ihr Code nur zur Verfügung steht, wenn das Dokument geöffnet ist.

Bibliotheken, die nicht in einem Dokument abgelegt sind (also allgemein oder für den aktuellen Benutzer verfübare Bibliotheken) werden im Folgenden als OpenOffice.org Bibliotheken zusammengefasst.

Der physische Speicherort für diese OpenOffice.org Bibliotheken wird unter
Extras > Optionen… > OpenOffice.org > Pfade > BASIC festgelegt.

Anmerkung: Hüten Sie sich, Bibliotheken auf Dateisystem-Ebene zu verschieben oder zu kopieren. Benutzen Sie stattdessen den Dialog "Makros verwalten" oder den Paket-Manager

Module in Biblitheken können maximal 64kb groß sein. Eine Bibliothek cann bis zu 16 000 Module enthalten. Weitere Infos finden Sie in der Online-Hilfe unter "Module und Bibliotheken" (???).


Die Entwicklungsumgebung (IDE)

Öffnen Sie die Entwicklungsumgebung:

  • in OOo 1.1.x unter Extras > Makros > Makro ...
  • in OOo 1.9.x und höher unter Extras > Makros > Makros verwalten > OpenOffice.org Basic...

Zum Einstieg benutzen wir das "Modul1" aus der Bibliothek "Standard" des aktuellen Benutzers:

Geben Sie einen Namen für das neue Makro ein: "HelloWorld"

Wählen Sie die Option Standard im Auswahlfeld "Makro aus:"

Klicken Sie auf Neu

Jetzt sollten Sie etwa folgendes sehen:

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

Sub Main

End Sub

Sub HelloWorld

End Sub

Der Cursor sollte am Anfang der Zeile Sub HelloWorld stehen.


Achtung: Das geöffnete IDE-Fenster ist sowohl über das Menü im OpenOffice.org-Fenster als auch über die Programmleiste des Betriebssystems erreichbar.


Eingeben von Programm-Code

Löschen Sie folgende Zeilen:

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

Sub Main

End Sub

Schreiben Sie unterhalb der Zeile "Sub HelloWorld": msgbox "Hello World!", so dass es in etwa so aussieht:

[oobas] Sub HelloWorld

 msgbox "Hello World!"

End Sub

Achtung: Die IDE beherrscht zwar keine "code completion" (Code-Vervollständigung ???) während der Eingabe, verfügt aber über eine kontext-sensitive Hilfe, wenn Sie während der Eingabe F1 oder "Hilfe" drücken oder der Cursor in einem Befehl steht.
Bei OpenOffice.org Basic-Befehlen wird die Groß- und Kleinschreibung nicht unterschieden. So sind die Eingaben msgbox, MSGBOX oder Msgbox äquivalent.
Stings (Textvariablen) werden in doppelte Anfürhrungszeichen eingeschlossen.


Den Code ausführen

Hierfür gibt es mehrere Möglichkeiten:

  • direkt aus der IDE: das Symbol Ausführen (das 3. Symbol in der 2. Leiste) ruft das ERSTE Makro des aktuellen Moduls auf.
  • aus dem Menü "Extras":
    • (Version 1.1.x) Extras > Makros > Makro…;
    • (Version 1.9.x und höher) Extras > Makro > Makro auführen…
  • Dem Makro ein Tastaturkürzel zuweisen (todo).
  • Dem Makro einen Menüeintrag zuweisen (todo).
  • Dem Makro ein Symbolleisten-Symbol zuweisen (todo).
  • Ein Kontroll-Element in einem Dokument erstellen (todo).
  • Das Makro einem Ereignis zuweisen (todo)

Führen Sie für den Anfang die "HelloWorld"-Subroutine aus, indem Sie auf das Ausführen-Symbol klicken. Ein kleiner Dialog mit dem Titel "soffice" und dem Text "Hello World" sollte aufpoppen.


Speichern des Code

Der Code wird immer automatisch gespeichert, wenn sein Container gespeichert wird. Wenn das Modul also in einer (allgemeinen oder benutzerspezifischen) OpenOffice.org-Bibliothek enthalten ist, wird es beim Schließen der Anwendung OpenOffice.org gespeichert. Entsprechend werden Dokument-interne Bibliotheken biem Speichern des Dokuments mit-gesichert.

Auf der Standard-Symbolleiste der IDE (normalerweise die oberste Symbolleiste) finden Sie ein Symbol "Speichern". Befindet sich der Code in einem Dokument oder einer Vorlage, dann speichert der Klick auf dieses Symbol das gesamte Dokument. Handelt es sich dagegen um eine OpenOffice.org-Bibliothek, wird nur die aktuelle Bibliothek gespeichert.


Variablen

Bei Variablen kann durch Option Explicit zu Beginn des Moduls die explizite Deklaration erzwungen werden. Zu Sinn und Unsinn des Deklarierens von Variablen lesen Sie diese Diskussion.

In dieser Diskussion vertritt der ursprüngliche Autor dieses Wiki-Beitrags die Position, dass Variablen immer deklariert werden sollten. Mittlerweile hat er seine Meinung geändert. Kurz: es ist eine Frage des persönlichen Geschmacks. Unabhängig davon sollten nach Auffassung des ursprünglichen Autors Variablen nach folgener Konvention benannt werden, die auch bei den Beispielen aus diesem Wiki verwendet wurde:

Der erste Buchstabe der Variable steht für den Typ des in der Variable gespeicherten Wertes. Dabei bezeichnen folgende Buchstaben die entsprechenden Datentypen (in Anlehung an das Tutorial.pdf von Sun):

Buchstabe Bedeutung
a Struktur (Structure)
b Bool'sch (WAHR oder FALSCH)
e Aufzählung (Enumeration). Diese Variable kann nur einen begrenzten Satz von Werten enthalten.
f Fließkomma-Zahl (3.402823 x 1038 bis 1.401298 x 10-45. Eine einzelne Variable kann bis zu 4 Bytes umfassen)
"Double" (doppelte Genauigkeit, 1.79769313486232 x 10308 bis 4.94065645841247 x 10-324. Eine Double-Variable kann bis zu 8 Bytes umfassen)
Währung (-922337203685477.5808 bis +922337203685477.5807 ebenfalls 8 Byte umfassend)
m Feld (Array) (aka Sequenz aka Matrix)
n Integer (-32768 to 32767.) oder
Long (-2147483648 and 2147483647).
o Objekt, Service oder Interface
s Text (String) (Eine String-Variable kann bis zu 65535 Unicode-Zeichen enthalten).
x Schnittstelle (Interface), um anzuzeigen, dass nur Methoden einer bstimmten Schnittstelle eines Objekts verwendet werden.
v Variant, irgend ein Typ

Benutzen Sie lange, beschreibende Variablennamen unter Verwendung von CamelCase (Groß-Klein-Schreibung).

Achtung: Bei benutzerdefinierten OpenOffice.org Basic-Variablen spielt die Groß-/Kleinschreibunge keine Rolle. Bei UNO-API-Konstanten aber sehr wohl!

Ausnahmen von der Regel, lange Namen zu verwenden, sind Index-Variablen (meist i, j oder k), sowie Strings (meist als s bezeichnet).

Bearbeiten Sie nun die sub HelloWorld, so dass der Code ungefähr wie im folgenden aussieht und führen Sie sie aus:

[oobas] sub HelloWorld dim i as integer 'This line is optional

 for i = 0 to 2
   'These lines are indented for ease of reading only
   'all your code should be like this for lonog time survival
   msgbox "Hello World " & i
 next i

end sub

Mehr Infos zur Verwendung von Variablen erhalten Sie in der Online-Hilfe unter "Variablen benutzen" (???)

Die OpenOffice.org API

Dieser Abschnitt beginnt mit einem Beispiel. Anschließend wird das Beispiel erläutert.

Versuchen Sie den folgenden Code in Dokumenten unterschiedlichen Typs auszuführen:

[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 = "Text"
  elseif thisComponent.supportsService("com.sun.star.sheet.SpreadsheetDocument") then
     fnWhichComponent = "Spreadsheet"
  elseif thisComponent.supportsService("com.sun.star.presentation.PresentationDocument") then
     fnWhichComponent = "Presentation"
  elseif thisComponent.supportsService("com.sun.star.drawing.GenericDrawingDocument") then
     fnWhichComponent = "Drawing"
  else
     fnWhichComponent = "Oops current document something else"
  end if

else

  fnWhichComponent = "Not a document"

end if End function


Namenskonventionen für Subroutinen

im obigen Beispiel beginnt die Benutzer-definierte Funktion mit den Buchstaben "fn". Diese Konvention (an die sich der ursprüngliche Autor hält) kennzeichnet eine Funktion als Benutzer-definiert. Entsprechend beginnt eine Benutzer-definierte Subroutine mit "sub". Diese im Folgenden benutzten Konventionen sollen Ihnen als Anfängern helfen, Benutzer-definierte von eingebauten Routinen/Funktionen zu unterscheiden.


Einführung in die OpenOffice.org API

In diesem Abschnitt werden folgende Begriffe erläutert:

  • Interface (Schnittstelle)
  • Modul
  • Service (Dienst)
  • Methode
  • Property (Eigenschaft)

Den Unterschied zwischen einem Interface und einem Service zu kennen, ist zwar nicht unbedingt Voraussetzung zum Programmieren unter OpenOffice.org, aber es hilft, die Dokumentation zu verstehen, und auch bei der Introspektion. Möglicherweise werden Sie den folgenden Abschnitt mindestens zwei mal lesen müssen!

Ein Interface (Schnittstelle) ist eine Definition eines Satzes von Methoden (und ihren Argumenten), die ein Service (Dienst), der dieses Interface implementiert, enthalten muss.

An interface is a definition of a set of methods (and their arguments) that a service which implements that interface must have.

Schnittstellen werden aus Benennungs-Gründen zu Modulen gruppiert. Alle Schnittstellen (und Dienste) beginnen mit "com.sun.star", dann folgt der Modul-Name, dann der Name der Schnittstelle (oder des Dienstes).

Beispielsweise bieten die meisten Dienste die Schnittstelle com.sun.star.beans.XPropertySet . Diese Schnittstelle ist im Modul "beans" gespeichert und ermöglicht Zugriff auf die Properties (Eigenschaften) eines Dienstes. Eine Eigenschaft ist ein Wert, eine Methode ist dagegen eine Aktion.

Ein OpenOffice.org-Objekt kann viele Dienste implementieren.

Ein OpenOffice.org-Objekt kann einen Dienst enthalten, der eine Schnittstelle implementiert, in welcher eine Methode beschreibt, dass ein anderes OpenOffice.org-Objekt zurückgegeben wird.

Introspektion

HasUnoInterfaces ist eine OpenOffice.org-Basic-Funktion zur Introspektion. Informieren Sie sich über [Introspektion in anderen Sprachen].

HasUnoInterfaces gibt true zurück wenn beim spezifizierten Objekt alle spezifizierten Schnittstellen verfügbar sind.

Die meisten OpenOffice.org-Objekte enthalten die Methode supportsService weil sie die Schnittstelle com.sun.star.lang.XServiceInfo enthalten.

Im obigen Beispiel prüft HasUnoInterfaces, ob das aktuelle Dokument die Schnittstelle com.sun.star.lang.XServiceInfo implementiert, da andernfalls die Methode supportsService fehlen würde. Der Aufruf dieser Methode würde in diesem Fall einen Laufzeitfehler verursachen.

supportsService ist eine Methode, die den Wert true zurückgibt, wenn der spezifizierte Service verfügbar ist. Das obige Beispiel prüft das Vorhandensein eines Service, um so den Typ des aktuell aktiven Dokuments zu bestimmen.

X-Ray tool

Using HasUnoInterfaces and supportsService gives information about an object at run time, but checking an object like this would be a nightmare for learning? Thankfully Bernard Marcelly has come to our rescue with the X-Ray tool. The X-Ray tool is available from: [ooomacros]. Download the zip file, unzip the document, open the document in OpenOffice.org, follow the instructions for installation and set-up.

Part of the X-Ray tool set-up is to specify a local copy of the OpenOffice.org SDK. Download the OpenOffice.org SDK from and extract it.

In the above example, at the start of the code, there are two commented lines (comments start with an apostrophe):

[oobas] 'basicLibraries.loadLibrary("Xray") 'xray.xray thisComponent Now that you have the X-Ray tool installed, uncomment these lines (remove the apostrophes) and rerun the macro. From version 5 of Xray the command simply becomes xray.

BasicLibraries is an OpenOffice.org Basic command that returns an object for accessing the OpenOffice.org libraries. The loadLibrary method ensures that the routines in that library are available for use.

xray.xray specifies the xray library and the xray subroutine within that library, thisComponent is the object that is being passed to xray for introspection.

To find the object that you want to work with often requires finding or creating it starting from either StarDesktop or thisComponent.


Desktop, documents, and current selection

StarDesktop and ThisComponent are OpenOffice.org Basic commands that refer to the application and currently active document respectively.

Unlike Microsoft Office, OpenOffice.org is one application with different components. When running some code it maybe useful to check which component is currently active. The above code demonstrates how that checking process can be done.

The Desktop that StarDesktop refers to is conceptual (historically it actually existed) and can be thought of as the OpenOffice.org application.


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.

Personal tools