Is Display.addFilter(...) the best way to add a glbal shortcut? I tried Display.addListener(...) but this didn't receive any events at all.
是的,通常Display.addFilter(...) 是添加glbal 快捷方式的最佳方式,因为它们比事件侦听器具有更高的偏好。请参阅Display.addFilter(...) javadoc 的以下评论。
因为事件过滤器在其他过滤器之前运行
监听器,事件过滤器都可以
阻止其他侦听器并设置
事件中的任意字段。为了
因此,事件过滤器都是
强大而危险。他们应该
通常为了性能而避免,
调试和代码维护
原因。
第二个问题:
Why don't I get the pressed character when I'm holding down ctrl? When I hold down alt or shift I get the expected mask and the pressed character.
问题是你看错了地方。而不是查询e.character,您应该使用e.keyCode。根据e.character 的javadoc,您不会只得到字符f:
根据事件,角色
由键入的键表示。
这是最后一个角色
所有修饰符后的结果
应用。例如,当用户
键入Ctrl+A,字符值为
0x01 (ASCII SOH)。
因此,当您按下 CTRL+f 时,它会转换为 0x06(ASCII ACK)。当您执行 ALT+f 或 SHIFT+f 时,情况并非如此.
另一方面,e.keyCode 的 javadoc 说:
根据事件,关键代码
键入的键,如定义的那样
通过类中的关键代码常量
SWT。当字符字段
事件不明确,这个字段
包含不受影响的值
原始字符。例如,
键入 Ctrl+M 或 Enter both 结果
字符 '\r' 但 keyCode
字段也将包含 '\r' 时
当 Ctrl+M 时输入了 Enter 和 'm'
已输入。
查看以下代码了解更多详情。对于演示,我尝试将监听器放在 Display 和 Test。
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class ControlF
{
public static void main(String[] args)
{
Display display = new Display ();
final Shell shell = new Shell (display);
final Color green = display.getSystemColor (SWT.COLOR_GREEN);
final Color orig = shell.getBackground();
display.addFilter(SWT.KeyDown, new Listener() {
public void handleEvent(Event e) {
if(((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'f'))
{
System.out.println("From Display I am the Key down !!" + e.keyCode);
}
}
});
shell.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if(((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'f'))
{
shell.setBackground(orig);
System.out.println("Key up !!");
}
}
public void keyPressed(KeyEvent e) {
if(((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'f'))
{
shell.setBackground(green);
System.out.println("Key down !!");
}
}
});
shell.setSize (200, 200);
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}