Just listed to the status of the UNO command directly, instead of trying to get something from a UI element (menu in this case, which may be customized, by the way).
Modify the following code as you need. Likely you will run StartControl
in the beginning of the processing that needs the function to be disabled; and then, you will call EndControl
in the end (making sure that it also executes in case of an error, using on error
statement).
Since registering a state listener automatically calls the first “status changes” event, the provided HelplinesFront_statusChanged
handler will automatically detect, if the status is incorrect, and dispatch the command. That will toggle the function, calling the handler again, but this time, it will see the disabled state, and do nothing.
Indeed, you may want to return the created listener from the StartControl
function, instead of storing it in a global variable; that would be preferable in case of a scoped task.
If you need to restore the previous state, you would need to have another Variant
variable, which would be set to the active command state in the HelplinesFront_statusChanged
handler (iif it was empty, i.e. in the very first call). Then EndControl
could check if it needs to dispatch the command again to restore the state back.
global g_listener
sub HelplinesFront_statusChanged(State)
if (State.FeatureURL.Main = ".uno:HelplinesFront") then
if (State.State) then
xDispatch = getDispatch(State.FeatureURL)
xDispatch.dispatch(State.FeatureURL, array())
end if
end if
end sub
sub HelplinesFront_disposing(Source)
g_listener = Empty
end sub
function getURLObject(urlString)
dim url as new com.sun.star.util.URL
url.Complete = urlString
xURLTransformer = CreateUnoService("com.sun.star.util.URLTransformer")
xURLTransformer.parseStrict(url)
getURLObject = url
end function
function getDispatch(url)
xComponent = ThisComponent
xController = xComponent.getCurrentController()
getDispatch = xController.queryDispatch(url, "_self", 0)
end function
sub StartControl
if (not IsEmpty(g_listener)) then EndControl
url = getURLObject(".uno:HelplinesFront")
xDispatch = getDispatch(url)
g_listener = CreateUnoListener("HelplinesFront_", "com.sun.star.frame.XStatusListener")
xDispatch.addStatusListener(g_listener, url)
end sub
sub EndControl
if (IsEmpty(g_listener)) then exit sub
url = getURLObject(".uno:HelplinesFront")
xDispatch = getDispatch(url)
xDispatch.removeStatusListener(g_listener, url)
g_listener = Empty
end sub