Detecting keypress when window isn't in focus

C

Chris Wilkins

I have a script which loops forever and I need a way to break out of
the loop with a keypress. I can do this with the script below and it
works fine, my problem is that if I take the focus away from the
command window that the script is running in, the keypress isn't
recognised and the loop doesn't end.

#!/usr/bin/perl -l

use strict;
use warnings;

use Win32::GuiTest qw/:ALL/;
use Term::ReadKey;

my $i = 0;

while (1)
{

ReadMode(3);
my $char = ReadKey(-1);
if ($char eq 'q')
{
last;
}
print $i;
sleep 1;
$i++;

}

Is there a way (with Term::ReadKey or anything else) of detecting a
keypress when the script window does not have focus?
 
Z

zentara

I have a script which loops forever and I need a way to break out of
the loop with a keypress. I can do this with the script below and it
works fine, my problem is that if I take the focus away from the
command window that the script is running in, the keypress isn't
recognised and the loop doesn't end.

#!/usr/bin/perl -l

use strict;
use warnings;

use Win32::GuiTest qw/:ALL/;
use Term::ReadKey;

my $i = 0;

while (1)
{

ReadMode(3);
my $char = ReadKey(-1);
if ($char eq 'q')
{
last;
}
print $i;
sleep 1;
$i++;

}

Is there a way (with Term::ReadKey or anything else) of detecting a
keypress when the script window does not have focus?

It looks like you are using Win32, so take this with a grain of salt,
I'm on Linux.

I don't know how Win32 does it, but you are looking for a global
keyboard grab, usually called grabGlobal. Be warned that it will
lock the keyboard from other apps.

You might want to look at defining window manager hotkeys, that
will let other apps run, by working at the window manager level.
Win32 must have some hotkey app you can run, but you will have to do
some work to let the hotkey find the app you are running.... maybe by
giving it a unique name?

zentara
 
J

Jürgen Exner

Chris Wilkins said:
Is there a way (with Term::ReadKey or anything else) of detecting a
keypress when the script window does not have focus?

AFAIK no because that keypress will go to whatever application currently
has the focus.

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top