B4J Question Trying to get coordinates of mouse click out of the application

LucaMs

Expert
Licensed User
Longtime User
Try this code and if it doesn't work, blame ChatGPT who just generated it, don't blame me ?

B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Show
    
    ' Inizializza il listener globale del mouse
    InitializeGlobalMouseListener(Me, "MouseClicked")
End Sub

' Questa Sub sarà chiamata quando un click del mouse globale viene intercettato
Sub MouseClicked(x As Double, y As Double)
    Log($"Mouse clicked at X=${x}, Y=${y}"$)
    ' Qui puoi aggiungere il codice per eseguire azioni specifiche
End Sub

#If JAVA
    import java.awt.Toolkit;
    import java.awt.event.AWTEventListener;
    import java.awt.event.MouseEvent;
    import anywheresoftware.b4j.objects.MouseClickListener;

    public static void InitializeGlobalMouseListener(Object b4jClassInstance, String b4jMethodName) {
        Toolkit.getDefaultToolkit().addAWTEventListener(
            new AWTEventListener() {
                @Override
                public void eventDispatched(AWTEvent event) {
                    if (event instanceof MouseEvent) {
                        MouseEvent mouseEvent = (MouseEvent) event;
                        double x = mouseEvent.getX();
                        double y = mouseEvent.getY();
                        try {
                            anywheresoftware.b4j.objects.MouseClickListener.class.getMethod(b4jMethodName, double.class, double.class)
                                .invoke(b4jClassInstance, x, y);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            },
            AWTEvent.MOUSE_EVENT_MASK
        );
    }
#End If
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User

I already see that the part explained in this thread is missing:
B4X:
https://www.b4x.com/android/forum/threads/inline-java-code.50141/#content
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…