Содержимое

# SFWidgets.ContextMenu service

Context menus are predefined at LibreOffice installation. They can be customized in the Tools + Customize dialog.

The ContextMenu service provides the following capabilities:

- Replace temporarily all the menu items of a specific context menu.

- Temporarily add new menu items at the bottom of a predefined context menu.

- Make the context menu temporarily inactive.

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.

## Service invocation

Before using the ContextMenu 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

##### В Basic

The ContextMenu service is instantiated from the SF_Document.ContextMenus() and SF_Datasheet.ContextMenus() methods only.

        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.

##### В 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()

## Properties

Name | Readonly | Type | Description
--- | --- | --- | ---
ParentDocument | Yes | Object | The parent document class (or one of its subclasses) instance.
ShortcutCharacter | Yes | String | Character used to define the access key of a menu item. The default character is ~.
SubmenuCharacter | Yes | String | Character or string that defines how menu items are nested. The default character is >.

## Menu and 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

The code below uses the default submenu character > to create the menu/submenu hierarchy defined above:

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

The string --- is used to define separator lines in menus or submenus.

## Using icons

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

## Methods

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.

### Синтаксис:

svc.Activate(opt enable: bool = True)

### Параметры:

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.

### Синтаксис:

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

### Параметры:

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.

### Пример:

##### В 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")

##### В 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.

### Синтаксис:

svc.RemoveAllItems()

### Пример:

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.

##### В 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

##### В 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)

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.

См. также

SFWidgets.PopupMenu service

SFWidgets.Menu service

Пожалуйста, поддержите нас!