2014-08-30 42 views
0

假设我在eclipse中运行我的程序,它将切换到mozilla窗口(它正在同时运行)。同样,当我们点击任务栏中的图标时。我已经尝试过Robot类来激发点击,但这是硬编码坐标到程序中,我不想这样做。如何在使用java的runnng windows应用程序之间切换?

任何建议如何我可以做到这一点。谢谢。

+1

我已经使用JNA或将我的Java程序与Windows实用程序编程语言(如AutoIt)链接。 – 2014-08-30 12:16:56

回答

0

我相信你的问题可能已经在这里回答:Active other process's window in Java

除此之外,JNA将是您最好的选择,核心Java或Java通常不允许 直接与操作系统进行交互,但JNA会这样做。

唯一的其他办法,我能想到的是调用应用程序,例如用命令铬像论点

try{ 
    Desktop.getDesktop().open(new File("Location\\to\\the\\program.exe")); 
} catch(IOException ex){ 
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 
} 

编辑(如果需要的话):

使用这种方法来调用它带参数

Process process = new ProcessBuilder("Location\\to\\the\\program.exe", 
      "param1","param2").start(); 
1

据我了解,你不能通过使用核心Java的名称切换到另一个正在运行的窗口。您可以通过通过机器人发送alt-tab键来切换窗口,但这不会显示命名窗口。为此,我建议使用JNI,JNA或某种操作系统特定的实用程序编程语言,例如AutoIt(如果这是Windows问题)。

例如,使用JNA,你可以做这样的事情:

import com.sun.jna.Native; 
import com.sun.jna.Pointer; 
import com.sun.jna.win32.StdCallLibrary; 

public class SetForgroundWindowUtil { 
    public interface User32 extends StdCallLibrary { 
     User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class); 

     interface WNDENUMPROC extends StdCallCallback { 
     boolean callback(Pointer hWnd, Pointer arg); 
     } 

     boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg); 

     int GetWindowTextA(Pointer hWnd, byte[] lpString, int nMaxCount); 

     int SetForegroundWindow(Pointer hWnd); 

     Pointer GetForegroundWindow(); 
    } 

    public static boolean setForegroundWindowByName(final String windowName, 
     final boolean starting) { 
     final User32 user32 = User32.INSTANCE; 
     return user32.EnumWindows(new User32.WNDENUMPROC() { 

     @Override 
     public boolean callback(Pointer hWnd, Pointer arg) { 
      byte[] windowText = new byte[512]; 
      user32.GetWindowTextA(hWnd, windowText, 512); 
      String wText = Native.toString(windowText); 
      // if (wText.contains(WINDOW_TEXT_TO_FIND)) { 
      if (starting) { 
       if (wText.startsWith(windowName)) { 
        user32.SetForegroundWindow(hWnd); 
        return false; 
       } 
      } else { 
       if (wText.contains(windowName)) { 
        user32.SetForegroundWindow(hWnd); 
        return false; 
       } 
      } 
      return true; 
     } 
     }, null); 
    } 

    public static void main(String[] args) { 
     boolean result = setForegroundWindowByName("Untitled", true); 
     System.out.println("result: " + result); 
    } 
} 

我不知道解决这个问题的任何操作系统无关的方式。

+0

谢谢,是的,你是对的我不能使用Alt + Tab(因为标签序列是未知的)。我想我必须看看JNA。 – Tairman 2014-09-01 06:27:40

相关问题