How can I trigger GetMouseButtonUp when the cursor leaves the game window? Or if the window is minimised, etc?

Hiya! I’m working on a game - not web based, will run fullscreen or in a window on the desktop - and I have what is essentially a click and drag functionality when you click and hold on the left mouse button. If the cursor leaves the window while dragging and then the mouse button is released out of the window, when the cursor is returned to the window the mouse still behaves as if the button is down i.e. still dragging while the mouse button is up.

To prevent this, is there a way to trigger the button release automatically when the cursor leaves the window? Or when the game window is minimised etc… Basically when the game loses focus, although I’m reluctant to say “loses focus” because I know that refers to something else to do with the GUI.

I feel like this must have been answered somewhere before, but I just haven’t found the right keyword yet. I know how to write the code for the mouse part, if someone could point me in the direction of some code that lets you know when the cursor isn’t on the window that would be amazing.

Thanks very much!

Romano

I don’t have sure, but I think that convert mouse position to viewport point and check if it out of bounds (< 0 or > 1)

var p = Camera.main.ScreenToViewportPoint(Input.mousePosition);
if (p.x < 0 || p.x > 1 || p.y < 0 || p.y > 1) Debug.Log("Is OUT");

Here’s my current solution, which is actually working pretty decently for the window being minimised, but doesn’t trigger anything when the mouse leaves the window yet.

Basically I have a boolean called

leftClickAndHoldActive

which is set to true when

Input.GetMouseButton(0)  // Left mouse button held down.

is true.

Then at the end of my code that detects different kinds of clicks (Single, double, leftclick and hold etc) I have this:

else if (leftClickAndHoldActive == true && !(Input.GetMouseButton(0)))
	{
              print("Lost Focus");
    }