Somehow reworked what I mostly already had:
Sub findDocAndHostingShapeForControlAndDoSomethingThen(pEvent)
On Local Error Goto fail
docAndShape = findDocAndHostingShapeForControl(pEvent)
REM Call myFullProgram(doAndShape)
fail:
End Sub
Function findDocAndHostingShapeForControl(pEvent)
Dim res()
findDocAndHostingShapeForControl = res
doc = pEvent.Source.Model.Parent.Parent.Parent
h = tryGetSheetForControl(doc, pEvent)
REM The line above only works for Calc documents, Otherwise it returns the Null object.
REM Still don't know how to do it for drawings. Would need to search all the pages.
If IsNull(h) Then
drPg = doc.DrawPage
Else
drPg = h.DrawPage
End If
shape = lookupDrawPageForShapeHostingControl(drPg, pEvent.Source.Model)
findDocAndHostingShapeForControl = Array(doc, shape)
End Function
Function lookupDrawPageForShapeHostingControl(pDrawPg, pModel) As Object
On Local Error Goto fail
u = pDrawPg.Count - 1
For j = 0 To u
j_sh = pDrawPg(j)
If j_sh.supportsService("com.sun.star.drawing.ControlShape") Then
j_ctrl = j_sh.Control
If EqualUnoObjects(j_ctrl, pModel) Then Exit For
End If
Next j
If j<=u Then lookupDrawPageForShapeHostingControl = j_sh
fail:
End Function
Function tryGetSheetForControl(pDoc, pEvent) As Object
On Local Error Goto fail
extAttribs = pEvent.Source.Peer.AccessibleContext.AccessibleParent.ExtendedAttributes
ctrlSheetName= Split(Split(extAttribs, ";")(0), ":")(1)
theCtrlSheet = pDoc.Sheets.GetByName(ctrlSheetName)
tryGetSheetForControl = theCtrlSheet
fail:
End Function
(I won’t actually need this often, but I did not want to have pieces all around another time.
The given solution is tested with Wiriter documents and with Calc documents. For me the Calc case is more important.)