How to have a script click/activate/invoke a button?

How do you fire off Button.OnClick() on a UI button from a script instead of actually clicking it?

My specific use case is that I’d like to have a button, any time it’s on screen, be invoked when the player pushes the ‘cancel’ button on whatever controller they’re using. But there might be other applications.

It has to call the actual OnClick() logic, as I need to use the same script on several buttons that have different behaviors in the Button Component in inspector.

// Trying this but OnClick() is not accessible

cancelButton = defaultInputActions.UI.Cancel;
cancelButton.Enable();
cancelButton.performed += GetComponent<Button>().OnClick();

Of course, I spend days trying to figure this out and wind up figuring out the solution two hours after asking here. Posting my own code in case anyone else winds up looking for this:

using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class AutoClickWithCancelButtonPress : MonoBehaviour {
    private DefaultInputActions defaultInputActions;
    private InputAction cancelButton;
    private Button button;
    
    void Awake()
    {
        defaultInputActions = new DefaultInputActions();
        button = GetComponent<Button>();
        cancelButton = defaultInputActions.UI.Cancel;
    }

    private void OnEnable()
    {
        cancelButton.Enable();
        cancelButton.performed += InvokeTheUiButton;
    }

    private void OnDisable()
    {
        cancelButton.Disable();
        cancelButton.performed += InvokeTheUiButton;
    }

    private void InvokeTheUiButton(InputAction.CallbackContext context)
    {
        button.onClick.Invoke();
    } }

Awake grabs the default input actions , the default cancel button, and the UI button we want to be invoked.
OnEnable and OnDisable will enable/disable the physical button and subscribe/unsubscribe the new method.
The new method, InvokeTheUiButton(), will act as a middleman, since the InputAction.CallbackContext context cannot be passed to the UI button’s Invoke() method.