There's this segment in this KidsCanCode tutorial that you can use to capture the mouse and also use the esc key to release the mouse. I found it works well! Maybe you can make use of for your next project too (check out the bit from 0:45)