Sumário

# SFWidgets.ContextMenu serviço

Os menus de contexto são predefinidos durante a instalação do LibreOffice. Eles podem ser personalizados na caixa de diálogo Ferramentas + Personalizar.

O serviço ContextMenu oferece os seguintes recursos:

- Substitua temporariamente todos os itens de um menu de contexto específico.

- Adicione temporariamente novos itens de menu na parte inferior de um menu de contexto predefinido.

- Desative temporariamente o menu de contexto.

The new menu settings are not saved anywhere. Neither in the document nor in the LibreOffice settings.

A context menu is usually triggered by a right-click on a specific area of a document. Consider clicking in a cell or on a sheet tab in a Calc document.

## Invocação do serviço

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

• 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

##### Em Basic

O serviço ContextMenu é instanciado apenas a partir dos métodos SF_Document.ContextMenus() e SF_Datasheet. ContextMenus().

        Sub DefineContextMenu()
            GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
            Dim calc As Object, menu As Object
            Set calc = CreateScriptService("Document", ThisComponent)
            Set menu = calc.ContextMenus("cell")  ' Right-click on a cell
            '  ... Define the context menu ...
            menu.Dispose()
        End Sub

Running the Sub defined above redefines the context menu related to a specific area in the document, here a cell belonging to a Calc document.

The new definition will remain active until the document is closed or until the context menu is redefined again.

Use the Dispose method to free resources after executing the context menu.

##### Em Python

The example above can be written in Python as follows:

        from scriptforge import CreateScriptService

        def DefineContextMenu(args=None):
            basic = CreateScriptService("Basic")
            calc = CreateScriptService("Document", basic.ThisComponent)
            menu = calc.ContextMenus("cell")  # Right-click on a cell
            #  ... Define the context menu ...
            menu.Dispose()

## Propriedades

Nome | Apenas leitura | Tipo | Descrição
--- | --- | --- | ---
ParentDocument | Sim | Object | The parent document class (or one of its subclasses) instance.
ShortcutCharacter | Sim | String | Caractere usado para definir a chave de acesso de um item de menu. O caractere padrão é ~.
SubmenuCharacter | Sim | String | Caractere ou string que define como itens do menu são aninhados. O caractere padrão é >.

## Menus e Submenus

To create a context menu with submenus, use the character defined in the SubmenuCharacter property while creating the menu entry to define where it will be placed. For instance, consider the following menu/submenu hierarchy.

        ' Item A
        ' Item B > Item B.1
        '          Item B.2
        ' ------ (line separator)
        ' Item C > Item C.1 > Item C.1.1
        '                     Item C.1.2
        ' Item C > Item C.2 > Item C.2.1
        '                     Item C.2.2
        '                     ------ (line separator)
        '                     Item C.2.3
        '                     Item C.2.4

O código abaixo usa o caractere padrão de submenu > para criar a hierarquia de menu/submenu definida acima:

        menu.AddItem("Item A")
        menu.AddItem("Item B>Item B.1")
        menu.AddItem("Item B>Item B.2")
        menu.AddItem("---")
        menu.AddItem("Item C>Item C.1>Item C.1.1")
        menu.AddItem("Item C>Item C.1>Item C.1.2")
        menu.AddItem("Item C>Item C.2>Item C.2.1")
        menu.AddItem("Item C>Item C.2>Item C.2.2")
        menu.AddItem("Item C>Item C.2>---")
        menu.AddItem("Item C>Item C.2>Item C.2.3")
        menu.AddItem("Item C>Item C.2>Item C.2.4")

A string --- é usada para definir linhas separadoras em menus ou submenus.

## Usando ícones

Unlike popup menus, context menu items must not contain any icons.

## Métodos

List of Methods in the ContextMenu Service
Activate | AddItem | RemoveAllItems

## Activate

Make the added items of the context menu stored in the document available for execution, or, at the opposite, disable them, depending on the argument.

### Sintaxe:

svc.Activate(opt enable: bool = True)

### Parâmetros:

enable: When True (default), the local menu stored in the document is made active. When False, the local menu is ignored and the global menu defined at LibreOffice level takes the precedence.

## AddItem

Inserts a menu entry in the context menu.

### Sintaxe:

svc.AddItem(menuitem: str, opt command: str, opt script: str)

### Parâmetros:

menuitem: Defines the text to be displayed in the menu. This argument also defines the hierarchy of the item inside the menu by using the submenu character. Set the last component to \"---\" to define a line separator.

command: The name of the UNO command that will be run when the item is clicked, without the .uno: prefix. If the command name does not exist or is not applicable, nothing will happen.

script: The URI for a Basic or Python script that will be executed when the item is clicked. Note that the given script will not get any argument.

### Exemplo:

##### Em Basic

          menu.AddItem(\"Menu top>Item 1\", command := \"About\")
          menu.AddItem("Menu top>Item 2", script := "vnd.sun.star.script:myLib.Module1.ThisSub?language=Basic&location=document")

##### Em Python

          menu.AddItem('Menu top>Item 1', command = 'About')
          menu.AddItem('Menu top>Item 2', script = 'vnd.sun.star.script:Module1.py$thisdef?language=Python&location=document')

## RemoveAllItems

Remove all items, both

- predefined with Tools + Customize and saved in the document

- added with contextmenu.AddItem()

This action cannot be reverted except by closing and reopening the document.

Afterwards, when relevant, use AddItem() to insert new menu items.

### Sintaxe:

svc.RemoveAllItems()

### Exemplo:

Associate next Sub/def with the on-right-click event of a sheet. The custom menu appears when right-clicking in column C of the Calc sheet, otherwise the normal behaviour is preserved.

##### Em Basic

          Sub OnRightClick1(Optional XRange)  '  Xrange is a com.sun.star.table.XCellRange object
          Dim calc As Object, menu As Object, in_column As Boolean
          Set calc = CreateScriptService("Calc", ThisComponent)
          Set menu = calc.ContextMenus("cell")
          menu.RemoveAllItems()
          in_column = ( Len(calc.Intersect("Sheet1.$C:$C", XRange.AbsoluteName)) > 0 )
          If in_column Then
              menu.AddItem("A", script := "vnd.sun.star.script:Standard.Module1.EnterA?language=Basic&location=document")
              ' ...
          End If
          menu.Activate(in_column)
          End Sub

##### Em Python

            def OnRightClick1(XRange = None)  #  Xrange is a com.sun.star.table.XCellRange object
                basic = CreateScriptService('basic')
                calc = CreateScriptService('Calc', basic.ThisComponent)
                menu = calc.ContextMenus('cell')
                menu.RemoveAllItems()
                in_column = ( len(calc.Intersect("Sheet1.$C:$C", XRange.AbsoluteName)) > 0 )
                if in_column:
                    menu.AddItem('A', script = 'vnd.sun.star.script:Module1.py$EnterA?language=Python&location=document")
                    # ...
                menu.Activate(in_column)

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.

Tópicos relacionados

Serviço SFWidgets.PopupMenu

Serviço SFWidgets.Menu

♥ Doe para nosso projeto! ♥