Problems using key emulator in Java
I am writing some Java code so that in the code, when an event happens, it opens Microsoft PowerPoint from the program and then emulates some key presses which are defined in the code. My problem is that when I ask it to emulate a key press and pass in the decimal value of the key I want it to emulate, it does it wrong.开发者_如何学Go The code is as follows:
public void test(String key) throws Exception {
int value = (int)key.charAt(0);
Controller c = new Controller();
Executer e = new Executer(c);
e.exec(c,"POWERPNT");
c.delay(5000);
c.emulateKeyTyped(97);
c.emulateKeyTyped(98);
}
The code above is meant to open Microsoft PowerPoint and emulate the keys 'a' and 'b' (whose ASCII values are '97' and '98'), but instead PowerPoint prints '1' and '2' and I have no idea why this is. This is using PowerPoint 2007. The odd thing is that if I replace the '97' by "KeyEvent.VK__A" (which is the same integer, ie. '97', since "KeyEvent.VK_A" returns an integer) then it prints the letter 'a' fine in PowerPoint. The reason I want to use integers is because it is being passed in from another part of the program and also because I want to be able to emulate key presses other than just letters/numbers etc. (Also arrows etc.)
I'm not sure if the problem is in the code or if it something to do with the PowerPoint 2007, but any help would be much appreciated.
Thanks for the answers so far,
This works for a through to z but I still can't get it to work for other values such as ? etc.
According to the documentation:
VK_A
thruVK_Z
are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
The integer values for the KeyEvent
constants for the alphabetic keys are the ASCII values for the uppercase letters not the lowercase ones.
This means you want to use 65 and 66 not 97 and 98.
The value of VK_A is ox41 = 65
. Hence, if you modify your code as:
c.emulateKeyTyped(65);
c.emulateKeyTyped(66);
then it should work fine.
Note this is just a logical conclusion from what you have written above, I don't know an iota about what a Controller
or an Executor
is!!
精彩评论