2016-07-09 13 views
0

私は画面2でJavaアプリケーションを実行しています。マウスを監視するようにアプリケーションのコードを追加したいです。私のウィンドウマシン)。Javaアプリケーションでデュアル画面の設定で単一画面にマウスをロックする

誰かが私にマウスを1つの画面にロックできるようにするコードを指摘できますか?

+2

私は、JavaがOSを知らない(「無関係」である)ように設計されているため、利用可能なツールの上位90%でさえ、このようなことを行うためのベストツールではないと感じています。 –

答えて

1

唯一の解決策は、マウスの位置を監視し、それが現在そのモニターにない場合は、メインモニターに戻すことです。ここでは、始めるためにいくつかのコードは次のとおりです。

import java.awt.AWTException; 
import java.awt.GraphicsDevice; 
import java.awt.GraphicsEnvironment; 
import java.awt.MouseInfo; 
import java.awt.PointerInfo; 
import java.awt.Robot; 

public class Main { 

    public static void main(String[] args) throws AWTException, InterruptedException { 
     //Get the primary monitor from the environment 
     GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); 
     //Create and start the thread that monitors the position of the mouse 
     Thread observerThread = new Thread(new Observer(gd)); 
     observerThread.start(); 

    } 

    private static class Observer implements Runnable{ 
     private GraphicsDevice mainMonitor; 
     private Robot robot; 
     int width, height; 

     public Observer(GraphicsDevice gd){ 
      mainMonitor = gd; 
      width = mainMonitor.getDisplayMode().getWidth(); 
      height = mainMonitor.getDisplayMode().getHeight(); 
      try { 
       robot = new Robot(); 
      } catch (AWTException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     @Override 
     public void run() { 
      while(true){ 
       //Check the monitor on which the mouse is currently displayed 
       PointerInfo pointerInfo = MouseInfo.getPointerInfo(); 
       GraphicsDevice device = pointerInfo.getDevice(); 
       if(!mainMonitor.equals(device)){ 
        //If the mouse is not on the primary monitor move it to the center of the primary monitor. 
        robot.mouseMove(width/2, height/2); 
       } 
       //Wait a while before checking the position of the mouse again. 
       try { 
        Thread.sleep(100); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

このアプローチに考慮すべきいくつかのものは:

  1. さまざまなモニタが同じ解像度を持っていない場合はどうすれば?これは、プライマリモニタから逸脱したときに、プライマリモニタの中心にマウスを移動することを選択した理由です。マウスの主画面へのロックに近いユーザーのための体験を作成しようとする場合は、マウスを主画面よりも大きいか小さい解像度の画面に移動したときに何をすべきかを判断する必要があります。

  2. 3台以上のモニターをお持ちの場合はどうなりますか?マウスの主要画面へのロックに近いユーザーのためのエクスペリエンスを作成しようとする場合は、モニタの相対的な位置を決定する方法が必要です。例えば。モニタ2はモニタ1の左側にあり、モニタ3はモニタ1の右にあるため、マウスがどの画面にあるかによって、マウスを適切な側のモニタ1の端に戻すことができます。

ご希望の場合は、この機能を使用してください。

関連する問題