俊星的BLOG

SWT试用之控制鼠标键盘

通过SWT可以控制鼠标键盘事件,具体如下:
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * 预期的运行效果为:显示开始菜单
 * 
@author kinkding
 * @history 2009-6-2
 
*/

public class MyEventRes {

    
public static void main(String[] args) {
        
final Display display = new Display();
        
final Shell shell = new Shell(display);
        
final Text text = new Text(shell, SWT.BORDER);
        text.setSize(text.computeSize(
150, SWT.DEFAULT));
        text.setText(
"神一样的人啊!");
        shell.pack();
        shell.open();

        
new KeyThread(display).start(); // 键盘响应
        
// new MouseThread(display).start(); // 鼠标响应
        while (!shell.isDisposed()) {
            
if (!display.readAndDispatch())
                display.sleep();
        }

        display.dispose();
    }

}


class MouseThread extends Thread {
    Display display;
    
int h;

    
public MouseThread(Display display) {
        
this.display = display;
        h 
= display.getPrimaryMonitor().getBounds().height;
    }


    
public void run() {
        Event event 
= new Event();
        
// 移动鼠标
        event.type = SWT.MouseMove;
        event.x 
= 5;
        event.y 
= h - 5;
        display.post(event);
        
try {
            Thread.sleep(
100);
        }
 catch (InterruptedException e) {
        }

        
// 按下右键
        event.type = SWT.MouseDown;
        event.button 
= 1;
        display.post(event);
        
try {
            Thread.sleep(
100);
        }
 catch (InterruptedException e) {
        }

        
// 恢复
        event.type = SWT.MouseUp;
        display.post(event);
    }

}


class KeyThread extends Thread {
    Display display;
    
int h;

    
public KeyThread(Display display) {
        
this.display = display;
        h 
= display.getPrimaryMonitor().getBounds().height;
    }


    
public void run() {
        Event event 
= new Event();
        
// 按下CTRL
        event.type = SWT.KeyDown;
        event.keyCode 
= SWT.CTRL;
        display.post(event);
        
try {
            Thread.sleep(
100);
        }
 catch (InterruptedException e) {
        }

        
// 按下ESC
        event.type = SWT.KeyDown;
        event.keyCode 
= SWT.ESC;
        display.post(event);
        
try {
            Thread.sleep(
100);
        }
 catch (InterruptedException e) {
        }

        
// 恢复
        event.type = SWT.KeyUp;
        event.keyCode 
= SWT.CTRL;
        display.post(event);
        
try {
            Thread.sleep(
100);
        }
 catch (InterruptedException e) {
        }

        event.type 
= SWT.KeyUp;
        event.keyCode 
= SWT.ESC;
        display.post(event);
    }

}

posted on 2009-06-02 00:15 俊星 阅读(797) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: