Serviço SFDialogs.Dialog

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

tip

Uma caixa de diálogo pode ser apresentada de forma modal ou não modal.


No modo modal, a caixa de diálogo é apresentada e a execução da macro é suspensa até que o botão OK ou Cancelar sejam pressionados. Enquanto isso, ações do usuário executadas na caixa de diálogo podem disparar ações específicas.

No modo não-modal a caixa de diálogo está "flutuando" no desktop do usuário e a execução do processo da macro continua normalmente. Um diálogo não-modal é fechado quando for finalizado com o método Terminate() ou quando a sessão LibreOfficeDev é encerrada. O botão de fechar a janela é inativo em diálogos não-modais.

Caixas de diálogo desaparecem da memória após serem explicitamente encerradas.

tip

O serviço SFDialogs.Dialog está intimamente relacionado ao serviço SFDialogs.DialogControl.


Invocação e Uso do Serviço

Antes de utilizar o serviço Dialog, a biblioteca ScriptForge deve ser carregada ou importada:

note

• Macros BASIC precisam carregar a biblioteca ScriptForge usando a seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Scripts Python exigem uma importação do módulo scriptforge:
from scriptforge import CreateScriptService


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

Container: "GlobalScope" para bibliotecas pré-instalados o um nome de janela definido pelo serviço ScriptForge.UI. O valor padrão é uma String vazia "", o que indica o documento atual.

Library: Nome da biblioteca contida no "Container" como uma string sensível à caixa. O valor padrão é "Standard".

DialogName: String sensível à caixa designando a caixa de diálogo.

Os exemplos abaixo em Basic e Python mostram o diálogo dlgConsole que pertence à biblioteca compartilhada ScriptForge:


      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")
      '... Inicialização dos controles vêm aqui...
      lButton = oDlg.Execute()
      'Modo padrão = Modal
      If lButton = oDlg.OKBUTTON Then
      '...Processa os controles e faz o que é necessário aqui...
      End If
      oDlg.Terminate()
  

Ou usando Python:


    dlg = CreateScriptService('SFDialogs.Dialog', 'GlobalScope', 'ScriptForge', 'dlgConsole')
    # ... Inicialização dos controles vem aqui...
    rc = dlg.Execute()
    # Modo padrão = Modal
    if rc == dlg.OKBUTTON:
        # ...Processa os controles e faz o que é necessário aqui...
    dlg.Terminate()
  
note

Use a string "GlobalScope" como o argumento container quando a caixa de diálogo estiver armazenada em Minhas macros e caixas de diálogo ou em Macros e diálogos da aplicação.


tip

The dialog service offers methods that create new controls dynamically in an existing dialog predefined with the Dialog Editor. A dialog is initialized with controls in the Dialog Editor and new controls can be added at run-time before or after the dialog Execute() statement.


The Dialog service can equally be invoked - through the CreateScriptService method - when creating dialogs on-the-fly. It requires two supplemental positional arguments after the name of the ad-hoc service "NewDialog":

DialogName: A case-sensitive string designating the dialog.

Place: Window location of the dialog being either :

All elements are expressed in Map AppFont units.


    Sub newDialog()
        Dim oDlg As Object
       oDlg = CreateScriptService("NewDialog", "myDialog1", Array(100,200, 40, 110))
       ' ...
    End Sub
  

Or using Python:


    def newDialog():
       dlg = CreateScriptService('NewDialog', 'myDialog1', (100,200, 40, 110))
       # ... Process controls and do what is needed
  

All properties and methods applicable to predefined dialogs are available for such new dialogs. In particular the series of CreateXXX() methods for the addition of new dialog controls.

Recuperando a instância Dialog que disparou um evento de diálogo

Uma instância do serviço Dialog pode ser obtida usando o serviço SFDialogs.DialogEvent, desde que o diálogo tenha sido inicializado usando o serviço Dialog. No exemplo abaixo, oDlg contém a instância Dialog que disparou o evento de diálogo.


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

Ou usando Python:


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

Note que nos exemplos anteriores o prefixo "SFDialogs." pode ser omitido quando for considerado apropriado.

Lidando com exceções em manipuladores de eventos

Ao criar um manipulador de evento para eventos de diálogo, considera-se boa prática tratar erros dentro da própria sub rotina. Por exemplo, suponha que o manipulador de eventos abaixo seja chamado quando o botão do mouse é pressionado na janela da caixa de diálogo.


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

Chame SF_Exception.Clear se você não quiser que o erro seja propagado após o término da execução do diálogo.


Em Python use blocos try/except nativos para tratar exceções conforme mostrado abaixo:


    def on_mouse_button_pressed(event=None):
        try:
            dlg = CreateScriptService("DialogEvent", event)
            # Processa o evento
        except Exception as e:
            # O objeto "bas" é uma instância do serviço Basic
            bas.MsgBox(str(e))
  

Propriedades

Nome

Somente leitura

Tipo

Descrição

OKBUTTON

Sim

Integer

Valor = 1. Um botão OK foi pressionado.

CANCELBUTTON

Sim

Integer

Valor = 0. Um botão Cancelar foi pressionado.

Caption

Não

String

Especifica o título da caixa de diálogo.

Height

Não

Long

Especifica a altura da caixa de diálogo.

Modal

Sim

Boolean

Especifica se a caixa de diálogo está em execução no formato "modal".

Name

Sim

String

Nome da caixa de diálogo

Page

Não

Integer

Uma caixa de diálogo pode ter várias páginas que podem ser percorridas pelo usuário uma a uma. A propriedade "Page" do objeto "Dialog" define qual página está ativa no diálogo.

Visible

Não

Boolean

Especifica se a caixa de diálogo está visível na área de trabalho. Por padrão, ela não é visível até que o método "Execute" seja invocado. Após isso, a caixa de diálogo passa a ser visível.

XDialogModel

Sim

UNO
object

Objeto UNO representando o modelo do diálogo. Consulte XControlModel e UnoControlDialogModel na documentação da API para mais detalhes.

XDialogView

Sim

UNO
object

Objeto UNO representando a visualização do diálogo. Consulte XControl e UnoControlDialog na documentação da API para mais detalhes.

Width

Não

Long

Especifica a largura da caixa de diálogo.


Propriedades de Evento

On… properties return a URI string with the reference to the script triggered by the event. On… properties can be set programmatically.
Read its specification in the scripting framework URI specification.

Nome

Read/Write

Descrição da IDE Basic

OnFocusGained

Sim

Quando receber o foco

OnFocusLost

Sim

Quando perder o foco

OnKeyPressed

Sim

Tecla pressionada

OnKeyReleased

Sim

Ao soltar uma tecla

OnMouseDragged

Sim

Quando mover o mouse com tecla pressionada

OnMouseEntered

Sim

Quando o mouse estiver dentro

OnMouseExited

Sim

Quando o mouse estiver fora

OnMouseMoved

Sim

Ao mover o mouse

OnMousePressed

Sim

Ao pressionar o botão do mouse

OnMouseReleased

Sim

Ao soltar o botão do mouse


warning

Assigning events via the Basic IDE and assigning events via macros are mutually exclusive.


Lista de métodos do serviço Dialog

Activate
Center
Controls
CloneControl
CreateButton
CreateCheckBox
CreateComboBox
CreateCurrencyField
CreateDateField
CreateFileControl
CreateFixedLine

CreateFixedText
CreateFormattedField
CreateGroupBox
CreateHyperlink
CreateImageControl
CreateListBox
CreateNumericField
CreatePatternField
CreateProgressBar
CreateRadioButton
CreateScrollBar

CreateTableControl
CreateTextField
CreateTimeField
CreateTreeControl
EndExecute
Execute
GetTextsFromL10N
Resize
OrderTabs
SetPageManager
Terminate


note

Dimensioning a dialog is done by using Map AppFont units. A dialog or control model also uses AppFont units. While their views use pixels.


Activate

Coloca o foco na instância Dialog atual. Retorna True se a focalização foi bem-sucedida.

Este método é chamado a partir de uma caixa de diálogo ou evento de controle, o quando um diálogo é apresentado no modo "não modal".

Sintaxe:

svc.Activate(): bool

Exemplo:


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

Exemplos em LibreOfficeDev Basic e Python assume que o diálogo é armazenado na biblioteca Standard do documento corrente.


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

Center

Centraliza a caixa de diálogo atual no centro de sua janela pai. Sem argumentos, o método centraliza a caixa de diálogo no meio da janela atual.

Retorna True se bem-sucedida.

Sintaxe:

svc.Center(opt Parent: obj): bool

Parâmetros:

Parent: Um objeto opcional que pode ser:

Exemplo:

Em Basic

     Sub TriggerEvent(oEvent As Object)
         Dim oDialog1 As Object, oDialog2 As Object, lExec As Long
         Set oDialog1 = CreateScriptService("DialogEvent", oEvent) ' Caixa de diálogo que causou o evento
         Set oDialog2 = CreateScriptService("Dialog", ...) ' Abre uma segunda caixa de diálogo
         oDialog2.Center(oDialog1)
         lExec = oDialog2.Execute()
         Select Case lExec
             ...
     End Sub
  
Em Python

     def triggerEvent(event: uno):
       dlg1 = CreateScriptService('DialogEvent.Dialog', event) # Caixa de diálogo que disparou o evento
       dlg2 = CreateScriptService('Dialog', ...) # Abre uma segunda caixa de diálogo
       dlg2.Center(dlg1)
       rc = dlg2.Execute()
       if rc is False:
         # ...
   

CloneControl

Duplicate an existing control of any type in the actual dialog. The duplicated control is left unchanged and can be relocated.

Sintaxe:

svc.CloneControl(SourceName: str, ControlName: str, Left: num, Top: num): svc

Parâmetros:

SourceName: The name of the control to duplicate.

ControlName: A valid control name as a case-sensitive string. It must not exist yet.

Left, Top: The coordinates of the new control expressed in Map AppFont units.

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

      Set myButton2 = oDlg.CloneControl("Button1", "Button2", 30, 30)
   
Em Python

     dlg = dlg.CloneControl('Button1', 'Button2', 30, 30)
   

Controls

Retorna:

Sintaxe:

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

svc.Controls(controlname: str): svc

Parâmetros:

ControlName : String sensível à caixa com o nome válido de um controle. Se não for especificado, a lista de nomes de controles é retornada em um Array indexado em zero.

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')
   

CreateButton

Create a new control of type Button in the current dialog.

Sintaxe:

svc.CreateButton(ControlName: str, Place: any, Toggle: bool = False, Push: str = ""): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Toggle: when True a Toggle button is created. Default = False

Push: "OK", "CANCEL" or "" (default)

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myButton = oDlg.CreateButton("Button1", Array(20, 20, 60, 15))
   
Em Python

     myButton = dlg.CreateButton('Button1', (20, 20, 60, 15))
   

CreateCheckBox

Create a new control of type CheckBox in the current dialog.

Sintaxe:

svc.CreateCheckBox(ControlName: str, Place: any, Multiline: bool = False): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

MultiLine: When True (default = False), the caption may be displayed on more than one line.

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myCheckBox = oDlg.CreateCheckBox("CheckBox1", Array(20, 20, 60, 15), MultiLine := True)
   
Em Python

     myCheckBox = dlg.CreateCheckBox('CheckBox1', (20, 20, 60, 15), MultiLine = True)
   

CreateComboBox

Create a new control of type ComboBox in the current dialog.

Sintaxe:

svc.CreateComboBox(ControlName: str, Place: any, Border: str = "3D", DropDown: bool = True, LineCount: num = 5): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

DropDown: When True (default), a drop down button is displayed

LineCount: Specifies the maximum line count displayed in the drop down (default = 5)

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myComboBox = oDlg.CreateComboBox("ComboBox1", Array(20, 20, 60, 15), Dropdown := True)
   
Em Python

     myComboBox = dlg.CreateComboBox('ComboBox1', (20, 20, 60, 15), Dropdown = True)
   

CreateCurrencyField

Create a new control of type CurrencyField in the current dialog.

Sintaxe:

svc.CreateCurrencyField(ControlName: str, Place: any, Border ="3D", SpinButton: bool = False, MinValue: num = -1000000, MaxValue: num = +1000000, Increment: num = 1, Accuracy: num = 2): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

SpinButton: when True (default = False), a spin button is present

MinValue: the smallest value that can be entered in the control. Default = -1000000

MaxValue: the largest value that can be entered in the control. Default = +1000000

Increment: the step when the spin button is pressed. Default = 1

Accuracy: specifies the decimal accuracy. Default = 2 decimal digits

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myCurrencyField = oDlg.CreateCurrencyField("CurrencyField1", Array(20, 20, 60, 15), SpinButton := True)
   
Em Python

     myCurrencyField = dlg.CreateCurrencyField('CurrencyField1', (20, 20, 60, 15), SpinButton = True)
   

CreateDateField

Create a new control of type DateField in the current dialog.

Sintaxe:

svc.CreateDateField(ControlName: str, Place: any, Border: str = "3D", DropDown: bool = False, opt MinDate: datetime, opt MaxDate: datetime): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

DropDown: when True (default = False), a dropdown button is shown

MinDate: the smallest date that can be entered in the control. Default = 1900-01-01

MaxDate: the largest date that can be entered in the control. Default = 2200-12-31

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myDateField = oDlg.CreateDateField("DateField1", Array(20, 20, 60, 15), Dropdown := True)
   
Em Python

     myDateField = dlg.CreateDateField('DateField1', (20, 20, 60, 15), Dropdown = True)
   

CreateFileControl

Create a new control of type FileControl in the current dialog.

Sintaxe:

svc.CreateFileControl(ControlName: str, Place: any, Border: str = "3D"): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myFileControl = oDlg.CreateFileControl("FileControl1", Array(20, 20, 60, 15))
   
Em Python

     myFileControl = dlg.CreateFileControl('FileControl1', (20, 20, 60, 15))
   

CreateFixedLine

Create a new control of type FixedLine in the current dialog.

Sintaxe:

svc.CreateFixedLine(ControlName: str, Place: any, Orientation: str): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Orientation: "H[orizontal]" or "V[ertical]".

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myFixedLine = oDlg.CreateFixedLine("FixedLine1", Array(20, 20, 60, 15), Orientation := "vertical")
   
Em Python

     myFixedLine = dlg.CreateFixedLine('FixedLine1', (20, 20, 60, 15), Orientation = 'vertical')
   

CreateFixedText

Create a new control of type FixedText in the current dialog.

Sintaxe:

svc.CreateFixedText(ControlName: str, Place: any, Border: str = "3D", MultiLine: bool = False, Align: str = "LEFT", VerticalAlign: str = "TOP"): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "NONE" (default) or "FLAT" or "3D"

Multiline: When True (default = False), the caption may be displayed on more than one line

Align: horizontal alignment, "LEFT" (default) or "CENTER" or "RIGHT"

VerticalAlign: vertical alignment, "TOP" (default) or "MIDDLE" or "BOTTOM"

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myFixedText = oDlg.CreateFixedText("FixedText1", Array(20, 20, 60, 15), MultiLine := True)
   
Em Python

     myFixedText = dlg.CreateFixedText('FixedText1', (20, 20, 60, 15), MultiLine = True)
   

CreateFormattedField

Create a new control of type FormattedField in the current dialog.

Sintaxe:

svc.CreateFormattedField(ControlName: str, Place: any, Border: str = "3D", SpinButton: bool = False, MinValue: num = -1000000, MaxValue: num = +1000000): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

SpinButton: when True (default = False), a spin button is present

MinValue: the smallest value that can be entered in the control. Default = -1000000

MaxValue: the largest value that can be entered in the control. Default = +1000000

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myFormattedField = oDlg.CreateFormattedField("FormattedField1", Array(20, 20, 60, 15), SpinButton := True)
   
Em Python

     myFormattedField = dlg.CreateFormattedField('FormattedField1', (20, 20, 60, 15), SpinButton = True)
   

CreateGroupBox

Create a new control of type GroupBox in the current dialog.

Sintaxe:

svc.CreateGroupBox(ControlName: str, Place: any): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myGroupBox = oDlg.CreateGroupBox("GroupBox1", Array(20, 20, 60, 15))
   
Em Python

     myGroupBox = dlg.CreateGroupBox('GroupBox1', (20, 20, 60, 15))
   

CreateHyperlink

Create a new control of type Hyperlink in the current dialog.

Sintaxe:

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "NONE" (default) or "FLAT" or "3D"

MultiLine: When True (default = False), the caption may be displayed on more than one line

Align: horizontal alignment, "LEFT" (default) or "CENTER" or "RIGHT"

VerticalAlign: vertical alignment, "TOP" (default) or "MIDDLE" or "BOTTOM"

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myHyperlink = oDlg.CreateHyperlink("Hyperlink1", Array(20, 20, 60, 15), MultiLine := True)
   
Em Python

     myHyperlink = dlg.CreateHyperlink('Hyperlink1', (20, 20, 60, 15), MultiLine = True)
   

CreateImageControl

Create a new control of type ImageControl in the current dialog.

Sintaxe:

svc.CreateImageControl(ControlName: str, Place: any, Border: str = "3D", Scale: str = "FITTOSIZE"): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

Scale: One of next values: "FITTOSIZE" (default), "KEEPRATIO" or "NO"

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myImageControl = oDlg.CreateImageControl("ImageControl1", Array(20, 20, 60, 15))
   
Em Python

       myImageControl = dlg.CreateImageControl('ImageControl1", (20, 20, 60, 15))
   

CreateListBox

Create a new control of type ListBox in the current dialog.

Sintaxe:

svc.CreateListBox(ControlName: str, Place: any, Border: str = "3D", DropDown: bool = True, LineCount: num = 5, MultiSelect: bool = False): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

DropDown: When True (default), a drop down button is displayed

LineCount: Specifies the maximum line count displayed in the drop down (default = 5)

MultiSelect: When True, more than 1 entry may be selected. Default = False

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myListBox = oDlg.CreateListBox("ListBox1", Array(20, 20, 60, 15), Dropdown := True, MultiSelect := True)
   
Em Python

     myListBox = dlg.CreateListBox('ListBox1', (20, 20, 60, 15), Dropdown = True, MultiSelect = True)
   

CreateNumericField

Create a new control of type NumericField in the current dialog.

Sintaxe:

svc.CreateNumericField(ControlName: str, Place: any, Border: str = "3D", SpinButton: bool = False, MinValue: num = -1000000, MaxValue: num = 1000000, Increment: num = 1, Accuracy: num = 2): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

SpinButton: when True (default = False), a spin button is present

MinValue: the smallest value that can be entered in the control. Default = -1000000

MaxValue: the largest value that can be entered in the control. Default = +1000000

Increment: the step when the spin button is pressed. Default = 1

Accuracy: specifies the decimal accuracy. Default = 2 decimal digits

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myNumericField = oDlg.CreateNumericField("NumericField1", Array(20, 20, 60, 15), SpinButton := True)
   
Em Python

     myNumericField = dlg.CreateNumericField('NumericField1', (20, 20, 60, 15), SpinButton = True)
   

CreatePatternField

Create a new control of type PatternField in the current dialog.

Sintaxe:

svc.CreatePatternField(ControlName: str, Place: any, Border: str = "3D", EditMask: str, opt LiteralMax: str): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

EditMask: a character code that determines what the user may enter
Refer to Pattern_Field in the wiki for more information.

LiteralMask: contains the initial values that are displayed in the pattern field

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myPatternField = oDlg.CreatePatternField("PatternField1", Array(20, 20, 60, 15), EditMask := "NNLNNLLLLL", LiteralMask := "__.__.2002")
   
Em Python

     myPatternField = dlg.CreatePatternField('PatternField1', (20, 20, 60, 15), EditMask = 'NNLNNLLLLL', LiteralMask = '__.__.2002')
   

CreateProgressBar

Create a new control of type ProgressBar in the current dialog.

Sintaxe:

svc.CreateProgressBar(ControlName: str, opt Place: any, Border: str = "3D", MinValue: num = 0, MaxValue: num = 100): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

MinValue: the smallest value that can be entered in the control. Default = 0

MaxValue: the largest value that can be entered in the control. Default = 100

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myProgressBar = oDlg.CreateProgressBar("ProgressBar1", Array(20, 20, 60, 15), MaxValue := 1000)
   
Em Python

     myProgressBar = dlg.CreateProgressBar('ProgressBar1', (20, 20, 60, 15), MaxValue = 1000)
   

CreateRadioButton

Create a new control of type RadioButton in the current dialog.

Sintaxe:

svc.CreateRadioButton(ControlName: str, Place: any, MultiLine: bool = False): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

MultiLine: When True (default = False), the caption may be displayed on more than one line

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myRadioButton = oDlg.CreateRadioButton("RadioButton1", Array(20, 20, 60, 15), MultiLine := True)
   
Em Python

     myRadioButton = dlg.CreateRadioButton('RadioButton1', (20, 20, 60, 15), MultiLine = True)
   

CreateScrollBar

Create a new control of type ScrollBar in the current dialog.

Sintaxe:

svc.CreateScrollBar(ControlName: str, Place, Orientation: str, Border: str = "3D", MinValue: num = 0, MaxValue: num = 100): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Orientation: H[orizontal] or V[ertical]

Border: "3D" (default) or "FLAT" or "NONE"

MinValue: the smallest value that can be entered in the control. Default = 0

MaxValue: the largest value that can be entered in the control. Default = 100

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myScrollBar = oDlg.CreateScrollBar("ScrollBar1", Array(20, 20, 60, 15), MaxValue := 1000)
   
Em Python

     myScrollBar = dialog.CreateScrollBar('ScrollBar1', (20, 20, 60, 15), MaxValue = 1000)
   

CreateTableControl

Create a new control of type TableControl in the current dialog.

Sintaxe:

svc.CreateTableControl(ControlName: str, Place: any, Border: str = "3D", RowHeaders: bool = True, ColumnHeaders: bool = True, ScrollBars: str = "N", GridLines: bool = False): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

RowHeaders: when True (default), the row Headers are shown

ColumnHeaders: when True (default), the column Headers are shown

ScrollBars: H[orizontal] or V[ertical] or B[oth] or N[one] (default). Scrollbars appear dynamically when they are needed.

GridLines: when True (default = False) horizontal and vertical lines are painted between the grid cells

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myTableControl = oDlg.CreateTableControl("TableControl1", Array(20, 20, 60, 15), ScrollBars := "B")
   
Em Python

     myTableControl = dlg.CreateTableControl('TableControl1', (20, 20, 60, 15), ScrollBars = 'B')
   

CreateTextField

Create a new control of type TextField in the current dialog.

Sintaxe:

svc.CreateTextField(ControlName: str, Place: any, Border: str = "3D", MultiLine: bool = False, MaximumLength: num = 0, PasswordCharacter: str = ""): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

MultiLine: When True (default = False), the caption may be displayed on more than one line

MaximumLength: the maximum character count (default = 0 meaning unlimited)

PasswordCharacter: a single character specifying the echo for a password text field (default = "")

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic
Set myTextField = oDlg.CreateTextField("TextField1", Array(20, 20, 120, 50), MultiLine := True)
   
Em Python

     myTextField = dlg.CreateTextField('TextField1', (20, 20, 120, 50), MultiLine = True)
   

CreateTimeField

Create a new control of type TimeField in the current dialog.

Sintaxe:

svc.CreateTimeField(ControlName: str, Place: any, Border: str = "3D", MinTime: num = 0, MaxTime: num = 24): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

MinTime: the smallest time that can be entered in the control. Default = 0

MaxTime: the largest time that can be entered in the control. Default = 24h

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myTimeField = oDlg.CreateTimeField("TimeField1", Array(20, 20, 60, 15))
   
Em Python

     myTimeField = dlog.CreateTimeField('TimeField1', (20, 20, 60, 15))
   

CreateTreeControl

Create a new control of type TreeControl in the current dialog.

Sintaxe:

svc.CreateTreeControl(ControlName: str, Place: any, Border = "3D"): svc

Parâmetros:

ControlName: the name of the new control. It must not exist yet.

Place: either …

All elements are expressed in Map AppFont units.

Border: "3D" (default) or "FLAT" or "NONE"

Valor de retorno:

An instance of SFDialogs.DialogControl service or Nothing.

Exemplo:

Em Basic

     Set myTreeControl = oDlg.CreateTreeControl("TreeControl1", Array(20, 20, 60, 15))
   
Em Python

     myTreeControl = dlg.CreateTreeControl('TreeControl1', (20, 20, 60, 15))
   

EndExecute

Finaliza a apresentação de um diálogo modal e retorna o argumento como valor de retorno da ação Execute() atual.

EndExecute() está geralmente contido no processamento da macro disparada por uma caixa de diálogo ou evento de controle.

Sintaxe:

svc.EndExecute(returnvalue: int)

Parâmetros:

returnvalue: Valor passado para o método Execute() em execução.

Exemplo:

Em 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
   
Em Python

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

As menções acima a com.sun.star.lang.EventObject são opcionais. Tais menções ajudam a identificar a API (Application Programming Interface) do LibreOfficeDev.


Execute

Mostra a caixa de diálogo, quando modal, e espera for sua finalização pelo usuário. O valor retornado é:

Para caixas de diálogo não modais o método sempre retorna 0 e a execução da macro continua.

Sintaxe:

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

Parâmetros:

modal: É False quando a caixa de diálogo for não modal. Padrão = True.

Exemplo:

Neste exemplo em Basic myDialog é armazenado na biblioteca Standard do documento corrente.


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

Este código em Python mostra o diálogo modal DlgConvert da biblioteca Basic compartilhada Euro.


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

GetTextsFromL10N

Substitui todas as strings de texto fixas em uma caixa de diálogo por suas versões traduzidas com base em uma instância de serviço L10N. Este método traduz as seguintes strings:

O método retorna True se for bem-sucedido.

Para criar uma lista de textos a traduzir numa caixa de diálogo, utilize o método AddTextsFromDialog do serviço L10N.

Sintaxe:

svc.GetTextsFromL10N(l10n: svc): bool

Parâmetros:

l10n: uma instância do serviço L10N do qual serão extraídas as strings a traduzir.

Exemplo:

O exemplo a seguir carrega strings traduzidas e as aplica à caixa de diálogo "MyDialog".

Em Basic

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

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

Acesse as páginas de ajuda do serviço L10N para saber mais sobre como os arquivos PO e POT são tratados.


OrderTabs

Set the tabulation index of a series of controls. The sequence of controls are given as an array of control names from the first to the last.

warning

Controls with an index >= 1 are not accessible with the TAB key if:
- they are omitted from the given list
- their type is FixedLine, GroupBox or ProgressBar
- they are disabled


Sintaxe:

svc.TabsList(TabsList: num, Start: num = 1, Increment: num = 1): bool

Parâmetros:

TabsList: an array of valid control names in the order of tabulation

Start: the tab index to be assigned to the 1st control in the list. Default = 1

Increment: the difference between 2 successive tab indexes. Default = 1

Valor de retorno:

True when successful.

Exemplo:

Em Basic

     oDlg.OrderTabs(Array("myListBox", "myTextField", "myNumericField"), Start := 10)
   
Em Python

     dlg.OrderTabs(('myListBox', 'myTextField', 'myNumericField'), Start = 10)
   

Resize

Moves the topleft corner of a dialog to new coordinates and/or modify its dimensions. All distances are expressed in AppFont units. 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: Distância horizontal do canto superior esquerdo.

Top: Distância vertical do canto superior esquerdo.

Width: Largura do retângulo que contém a caixa de diálogo.

Height: Altura do retângulo que contém a caixa de diálogo.

Missing arguments are left unchanged

Exemplo:

Em Basic

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

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

SetPageManager

Define quais controles em um diálogo são responsáveis por mudar de página, tornando mais fácil gerenciar a propriedade Page da caixa de diálogo e de seus controles.

Caixas de diálogo podem ter múltiplas páginas e a página visível é definida pela propriedade Page do diálogo. Se a propriedade Page não for modificada, a página visível padrão é igual a 0 (zero), o que significa que nenhuma página em particular está definida e todos os controles visíveis são mostrados independentemente de seus próprios valores da propriedade Page.

Quando a propriedade Page de um diálogo é modificada para um valor como 1, 2, 3 e assim por diante, então apenas os controles cujo valor Page forem iguais ao valor de página do diálogo serão mostrados.

Ao usar o método SetPageManager é possível definir quatro tipos de gerenciadores de página:

tip

É possível usar mais de um mecanismo de gerenciamento de página ao mesmo tempo.


Este método deve ser chamado apenas uma vez antes de chamar o método Execute. As chamadas subsequentes são ignoradas.

Se for bem sucedido, este método retorna True.

Sintaxe:

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

Parâmetros:

pilotcontrols: uma lista separada por vírgulas de nomes de controle ListBox, ComboBox ou RadioButton usados como gerenciadores de página. Para controles RadioButton, especifique o nome do primeiro controle no grupo a ser usado.

tabcontrols: uma lista separada por vírgulas de nomes de botões que serão usados como gerenciadores de página. A ordem em que são especificados neste argumento corresponde ao número da página a que estão associados.

wizardcontrols: uma lista separada por vírgulas com os nomes de dois botões que serão usados para os botões Anterior/Próximo.

lastpage: o número da última página disponível. Recomenda-se especificar esse valor ao usar o gerenciador de páginas Anterior/Próxima.

Exemplo:

Considere um diálogo com três páginas. A caixa de diálogo possui um controle ListBox chamado "aPageList" que será usado para controlar a página visível. Além disso, há dois botões denominados "btnPrevious" e "btnNext" que serão usados como botões Anterior/Próximo na caixa de diálogo.

Em Basic

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

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

Terminate

Finaliza o serviço Dialog para a instância atual. Retorna True se a finalização foi bem-sucedida.

Sintaxe:

svc.Terminate(): bool

Exemplo:

Os exemplos abaixo em Basic e Python abrem os diálogos não-modais DlgConsole e dlgTrace. Eles são armazenados, respectivamente, nas bibliotecas compartilhadas ScriptForge e Access2Base. Os botões de fechamento do diálogo são desabilitados e a terminação explícita é realizada ao final da execução do processo.

Neste exemplo um botão em DlgConsole está substituindo o fechamento inibido da janela:

Em Basic

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

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

Todas as rotinas ou identificadores do ScriptForge em Basic que possuem o caractere "_" como prefixo são reservadas para uso interno. Elas não devem ser usadas em macros escritas em Basic ou em Python.