Conteúdo
Índice 🔎︎

# SFDialogs.Dialog service

The Dialog service contributes to the management of dialogs created with the Basic Dialog Editor. Each instance of the current class represents a single dialog box displayed to the user.

A dialog box can be displayed in modal or in non-modal modes.

In modal mode, the box is displayed and the execution of the macro process is suspended until one of the OK or Cancel buttons is pressed. In the meantime, user actions executed on the box can trigger specific actions.

In non-modal mode, the dialog box is "floating" on the user desktop and the execution of the macro process continues normally. A non-modal dialog closes when it is terminated with the Terminate() method or when the LibreOffice session ends. The window close button is inactive in non-modal dialogs.

A dialog box disappears from memory after its explicit termination.

The SFDialogs.Dialog service is closely related to the SFDialogs.DialogControl service.

## Service invocation and usage

Before using the Dialog service the ScriptForge library needs to be loaded or imported:

• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService

The Dialog service is invoked through the CreateScriptService method. It requires three positional arguments to specify the dialog box to activate:

Container: "GlobalScope" for preinstalled libraries or a window name as defined by ScriptForge.UI service. Empty string "" default value stands for the current document.

Library: The case-sensitive name of a library contained in the container. Default value is "Standard".

DialogName: A case-sensitive string designating the dialog.

The examples below in Basic and Python display the dlgConsole dialog that belongs to the ScriptForge shared library:

          Dim oDlg As Object, lButton As Long
          Dim Container As String, Library As String, DialogName As String
          Set oDlg = CreateScriptService("SFDialogs.Dialog", "GlobalScope", "ScriptForge", "dlgConsole")
          '... controls initialization goes here...
          lButton = oDlg.Execute()
          'Default mode = Modal
          If lButton = oDlg.OKBUTTON Then
          '... Process controls and do what is needed here
          End If
          oDlg.Terminate()

Or using Python:

        dlg = CreateScriptService('SFDialogs.Dialog', 'GlobalScope', 'ScriptForge', 'dlgConsole')
        # ... controls initialization goes here...
        rc = dlg.Execute()
        # Default mode is Modal
        if rc == dlg.OKBUTTON:
            # ... Process controls and do what is needed here
        dlg.Terminate()

Use the string "GlobalScope" as the container argument when the dialog is stored either in My Macros & Dialogs or in Application Macros & Dialogs.

## Retrieving the Dialog instance that triggered a dialog event

An instance of the Dialog service can be retrieved via the SFDialogs.DialogEvent service, provided that the dialog was initiated with the Dialog service. In the example below, oDlg contains the Dialog instance that triggered the dialog event.

        Sub aDialogEventHander(ByRef poEvent As Object)
            Dim oDlg As Object
            Set oDlg = CreateScriptService("SFDialogs.DialogEvent", poEvent)
            ' ...
        End Sub

Or using Python:

        def control_event_handler(event: uno):
            dlg = CreateScriptService("SFDialogs.DialogEvent", event)
            # ...

Note that in the previous examples, the prefix "SFDialogs." may be omitted when deemed appropriate.

## Handling exceptions in event handlers

When creating an event handler for dialog events it is good practice to handle errors inside the subroutine itself. For instance, suppose the event handler below is called when the mouse button is pressed in the dialog window.

        Sub OnMouseButtonPressed(ByRef oEvent As Object)
        On Local Error GoTo Catch
            Dim oDialog As Object
            oDialog = CreateScriptService("DialogEvent", oEvent)
            ' Process the event
            Exit Sub
        Catch:
            MsgBox SF_Exception.Description
            SF_Exception.Clear
        End Sub

Call SF_Exception.Clear if you do not want the error to propagate after the dialog execution ended.

In Python use native try/except blocks for exception handling as shown below:

        def on_mouse_button_pressed(event=None):
            try:
                dlg = CreateScriptService("DialogEvent", event)
                # Process the event
            except Exception as e:
                # The object "bas" is an instance of the Basic service
                bas.MsgBox(str(e))

## Properties

Name | ReadOnly | Type | Description
--- | --- | --- | ---
OKBUTTON | Yes | Integer | Value = 1. An OK button was pressed.
CANCELBUTTON | Yes | Integer | Value = 0. A Cancel button was pressed.
Caption | No | String | Specify the title of the dialog.
Height | No | Long | Specify the height of the dialog box.
Modal | Yes | Boolean | Specifies if the dialog box is currently in execution in modal mode.
Name | Yes | String | The name of the dialog
Page | No | Integer | A dialog may have several pages that can be traversed by the user step by step. The Page property of the Dialog object defines which page of the dialog is active.
Visible | No | Boolean | Specify if the dialog box is visible on the desktop. By default it is not visible until the Execute() method is run and visible afterwards.
XDialogModel | Yes | UNO object | The UNO object representing the dialog model. Refer to XControlModel and UnoControlDialogModel in Application Programming Interface (API) documentation for detailed information.
XDialogView | Yes | UNO object | The UNO object representing the dialog view. Refer to XControl and UnoControlDialog in Application Programming Interface (API) documentation for detailed information.
Width | No | Long | Specify the width of the dialog box.

## Event properties

Returns a URI string with the reference to the script triggered by the event. Read its specification in the scripting framework URI specification.

Name | ReadOnly | Basic IDE Description
--- | --- | ---
OnFocusGained | Yes | When receiving focus
OnFocusLost | Yes | When losing focus
OnKeyPressed | Yes | Key pressed
OnKeyReleased | Yes | Key released
OnMouseDragged | Yes | Mouse moved while key presses
OnMouseEntered | Yes | Mouse inside
OnMouseExited | Yes | Mouse outside
OnMouseMoved | Yes | Mouse moved
OnMousePressed | Yes | Mouse button pressed
OnMouseReleased | Yes | Mouse button released

List of Methods in the Dialog Service
Activate Center Controls | EndExecute Execute GetTextsFromL10N | Resize SetPageManager Terminate

## Activate

Set the focus on the current Dialog instance. Return True if focusing was successful.

This method is called from a dialog or control event, or when a dialog is displayed in non-modal mode.

### Sintaxe:

svc.Activate(): bool

### Exemplo:

          Dim oDlg As Object
          Set oDlg = CreateScriptService(,, "myDialog")
          oDlg.Execute()
          ' ...
          oDlg.Activate()

Python and LibreOffice Basic examples both assume that the dialog is stored in current document's Standard library.

         dlg = CreateScriptService(,,'myDialog')
         dlg.Execute()
         # ...
         dlg.Activate()

## Center

Centers the current dialog instance in the middle of a parent window. Without arguments, the method centers the dialog in the middle of the current window.

Returns True when successful.

### Sintaxe:

svc.Center(opt Parent: obj): bool

### Parâmetros:

Parent: An optional object that can be either …

- a ScriptForge dialog object

- a ScriptForge document (Calc, Base, ...) object

### Exemplo:

##### In Basic

         Sub TriggerEvent(oEvent As Object)
             Dim oDialog1 As Object, oDialog2 As Object, lExec As Long
             Set oDialog1 = CreateScriptService("DialogEvent", oEvent) ' The dialog that caused the event
             Set oDialog2 = CreateScriptService("Dialog", ...) ' Open a second dialog
             oDialog2.Center(oDialog1)
             lExec = oDialog2.Execute()
             Select Case lExec
                 ...
         End Sub

##### In Python

         def triggerEvent(event: uno):
           dlg1 = CreateScriptService('DialogEvent.Dialog', event)  # The dialog having caused the event
           dlg2 = CreateScriptService('Dialog', ...)  # Open a second dialog
           dlg2.Center(dlg1)
           rc = dlg2.Execute()
           if rc is False:
             # ...

## Controls

Return either:

- the list of the controls contained in the dialog

- a DialogControl class instance based on its name

### Sintaxe:

svc.Controls(): str[0..*]

svc.Controls(controlname: str): svc

### Parâmetros:

ControlName : A valid control name as a case-sensitive string. If absent, the list of control names is returned as a zero-based array.

### Exemplo:

          Dim myDialog As Object, myList As Variant, myControl As Object
          Set myDialog = CreateScriptService("SFDialogs.Dialog", , "Standard", "Dialog1")
          myList = myDialog.Controls()
          Set myControl = myDialog.Controls("myTextBox")

         dlg = CreateScriptService('SFDialogs.Dialog','', 'Standard', 'Dialog1')
         ctrls = dlg.Controls()
         ctrl = dlg.Controls('myTextBox')

## EndExecute

Ends the display of a modal dialog and gives back the argument as return value for the current Execute() running action.

EndExecute() is usually contained in the processing of a macro triggered by a dialog or control event.

### Sintaxe:

svc.EndExecute(returnvalue: int)

### Parâmetros:

returnvalue: The value passed to the running Execute() method.

### Exemplo:

Using LibreOffice Basic:

          Sub OnEvent(poEvent As com.sun.star.lang.EventObject)
              Dim oDlg As Object
              Set oDlg = CreateScriptService("SFDialogs.DialogEvent", poEvent)
              oDlg.EndExecute(ReturnValue := 25)
          End Sub

Using Python:

         from com.sun.star.lang import EventObject
         def on_event(event: EventObject):
             dlg = CreateScriptService("SFDialogs.DialogEvent", event)
             dlg.EndExecute(25)

Above com.sun.star.lang.EventObject mentions are optional. Such annotations help identify LibreOffice Application Programming Interface (API).

## Execute

Display the dialog box and, when modal, wait for its termination by the user. The returned value is either:

- 0 : Cancel button pressed

- 1 : OK button pressed

- Otherwise the dialog stopped with an EndExecute() statement issued by a dialog or control event

For non-modal dialog boxes the method always returns 0 and the execution of the macro continues.

### Sintaxe:

svc.Execute(modal: bool = True): int

### Parâmetros:

modal: False when non-modal dialog. Default = True.

### Exemplo:

In this Basic example myDialog dialog is stored in current document's Standard library.

          Dim oDlg As Object, lReturn As Long
          Set oDlg = CreateScriptService("SFDialogs.Dialog", , , "myDialog")
          lReturn = oDlg.Execute(Modal := False)
          Select Case lReturn
              ' ...
          End Select

This Python code displays DlgConvert modal dialog from Euro shared Basic library.

         dlg = CreateScriptService("SFDialogs.Dialog", 'GlobalScope', 'Euro', "DlgConvert")
         rc = dlg.Execute()
         if rc == dlg.CANCELBUTTON:
             # ...

## GetTextsFromL10N

Replaces all fixed text strings in a dialog by their translated versions based on a L10N service instance. This method translates the following strings:

- The title of the dialog.

- The caption of the following control types: Button, CheckBox, FixedLine, FixedText, GroupBox and RadioButton.

- Static strings in ListBoxes and ComboBoxes.

- The tooltip or help text displayed when the mouse hovers over the control.

The method returns True if successful.

To create a list of translatable strings in a dialog use the AddTextsFromDialog method from the L10N service.

### Sintaxe:

svc.GetTextsFromL10N(l10n: svc): bool

### Parâmetros:

l10n: A L10N service instance from which translated strings will be retrieved.

### Exemplo:

The following example loads translated strings and applies them to the dialog "MyDialog".

##### In Basic

         oDlg = CreateScriptService("Dialog", "GlobalScope", "Standard", "MyDialog")
         myPO = CreateScriptService("L10N", "/home/user/po_files/")
         oDlg.GetTextsFromL10N(myPO)
         oDlg.Execute()

##### In Python

         dlg = CreateScriptService("Dialog", "GlobalScope", "Standard", "MyDialog")
         myPO = CreateScriptService("L10N", "/home/user/po_files/")
         dlg.GetTextsFromL10N(myPO)
         dlg.Execute()

Read the L10N service help page to learn more about how PO and POT files are handled.

## Resize

Moves the topleft corner of a dialog to new coordinates and/or modify its dimensions. All distances are expressed in 1/100 mm. Without arguments, the method resets the initial dimensions. Return True if the resize was successful.

### Sintaxe:

svc.Resize(opt Left: num, opt Top: num, opt Width: num, opt Height: num): bool

### Parâmetros:

Left: the horizontal distance from the top-left corner

Top: the vertical distance from the top-left corner

Width: the width of the rectangle containing the dialog

Height: the height of the rectangle containing the dialog

Negative or missing arguments are left unchanged

### Exemplo:

##### In Basic

         oDialog.Resize(1000, 2000, Height := 6000) ' Width is not changed

##### In Python

With Python:

         oDialog.Resize(1000, 2000, Height = 6000)  # Width is not changed

## SetPageManager

Defines which controls in a dialog are responsible for switching pages, making it easier to manage the Page property of a dialog and its controls.

Dialogs may have multiple pages and the currently visible page is defined by the Page dialog property. If the Page property is left unchanged, the default visible page is equal to 0 (zero), meaning that no particular page is defined and all visible controls are displayed regardless of the value set in their own Page property.

When the Page property of a dialog is changed to some other value such as 1, 2, 3 and so forth, then only the controls whose Page property match the current dialog page will be displayed.

By using the SetPageManager method it is possible to define four types of page managers:

- List box or combo box: in this case, each entry in the list box or combo box corresponds to a page. The first item refers to Page 1, the second items refers to Page 2 and so on.

- Group of radio buttons: defines a group of radio buttons that will control which page is visible.

- Sequence of buttons: defines a set of buttons, each of which corresponding to a dialog page. This can be used to emulate a tabbed interface by placing buttons side by side in the dialog.

- Previous/Next buttons: defines which buttons in the dialog that will be used to navigate to the Previous/Next page in the dialog.

It is possible to use more than one page management mechanism at the same time.

This method is supposed to be called just once before calling the Execute method. Subsequent calls are ignored.

If successful this method returns True.

### Sintaxe:

svc.SetPageManager(pilotcontrols: str = "", tabcontrols: str = "", wizardcontrols: str = "", opt lastpage: int): bool

### Parâmetros:

pilotcontrols: a comma-separated list of ListBox, ComboBox or RadioButton control names used as page managers. For RadioButton controls, specify the name of the first control in the group to be used.

tabcontrols: a comma-separated list of button names that will be used as page managers. The order in which they are specified in this argument corresponds to the page number they are associated with.

wizardcontrols: a comma-separated list with the names of two buttons that will be used as the Previous/Next buttons.

lastpage: the number of the last available page. It is recommended to specify this value when using the Previous/Next page manager.

### Exemplo:

Consider a dialog with three pages. The dialog has a ListBox control named "aPageList" that will be used to control the visible page. Additionally, there are two buttons named "btnPrevious" and "btnNext" that will be used as the Previous/Next buttons in the dialog.

##### In Basic

        oDialog.SetPageManager(PilotControls := "aPageList", _
                               WizardControls := "btnPrevious,btnNext", _
                               LastPage := 3)
        oDialog.Execute()

##### In Python

        dlg.SetPageManager(pilotcontrols="aPageList",
                           wizardcontrols="btnPrevious,btnNext",
                           lastpage=3)
        dlg.Execute()

## Terminate

Terminate the Dialog service for the current instance. Return True if the termination was successful.

### Sintaxe:

svc.Terminate(): bool

### Exemplo:

Below Basic and Python examples open DlgConsole and dlgTrace non-modal dialogs. They are respectively stored in ScriptForge and Access2Base shared libraries. Dialog close buttons are disabled and explicit termination is performed at the end of a running process.

In this example a button in DlgConsole is substituting inhibited window closing:

##### In Basic

         oDlg = CreateScriptService("SFDialogs.Dialog","GlobalScope","ScriptForge","DlgConsole")
         oDlg.Execute(modal:=False)
         Wait 5000
         oDlg.Terminate()

With Python:

##### In Python

         from time import sleep
         dlg = CreateScriptService('SFDialogs.Dialog',"GlobalScope",'Access2Base',"dlgTrace")
         dlg.Execute(modal=False)
         sleep 5
         dlg.Terminate()

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.

Tópicos relacionados

SFDialogs.DialogControl service

ScriptForge.UI service