How to tell if the mouse is over the window?

I looked through the reference and I don’t see anything for that. Do I just need to use mouseEnter() and mouseLeave() events? :confused:

yes, very good question,
as this:

void setup() {
  size (200, 200);
}

int ccol = 0;

void draw() {
  if ( overmyWindow() ) { ccol = 200; } else { ccol = 0; }
  background(0, ccol, 0);
}

boolean overmyWindow() {
  println(" mouseX "+mouseX+" mouseY "+mouseY);
  if ( (mouseX > 2) && (mouseX <= width -2) && (mouseY > 2)  && (mouseY <= height -2) )   return true;
  return false;
}

only works as long you move the mouse very slow over the
window border.

But what is a real bad thing:
it still works if the drawing window is NOT the activ one.

//__ system_info
processing 3.4 JAVA mode
windows 7

If you add “focused” to your overMyWindow if statement, then it should return only if the sketch is focused.

2 Likes

…Isn’t there a better way though? Even if I have to dig into the underlying window code or whatever? Or do I just need to add a pause button? :confused:

Edit: Hmm. I’m digging into the javadoc, and I would expect either PApplet of PSurface to have his functionality, but it doesn’t look like either of them do.

Alright, I added this functionality myself with:

public boolean mousePresent = true;
    
    public void mouseExited() {
    	mousePresent = false;
    }
    
    public void mouseEntered() {
    	mousePresent = true;
    }
3 Likes

cool, where you find this?

https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html#mouseEntered(java.awt.event.MouseEvent)

i can now use:

  ccol = ( focused && mousePresent ) ? 255 : 0;
  background(0, ccol, 0);

I don‘t quite know what Would be better. I mean, you can get if the window is focused and if the mouse is inside the bounds… not much more needed to see if it‘s focused and within bounds :sweat_smile:

Well no, if the mouse goes outside the window, it leaves mouseX and mouseY at whatever they were before it left the window. And focused stays true until you click on something else. So if you check both of those, then move the mouse outside the window but don’t click on anything… It still registers as inside. Which, in combination with my panning code, means it will continue panning even after the mouse has left the window.

As for where I found my last code? I just made it up. It’s pretty standard though, you’ll see basically that all over the place.

1 Like

Oh Yeah, didn‘t think about focused not changing without clicking outside :sweat_smile: Anyway, good to know that mouseEntered is a thing :blush: