繁体   English   中英

如何使用Java在Runnng Windows应用程序之间切换?

[英]How to switch between runnng windows applications using java?

假设我在eclipse中运行我的程序,它将切换到mozilla窗口(它正在同时运行)。 同样,当我们单击任务栏中的图标时。 我曾尝试使用Robot类来刺激点击,但这是将坐标硬编码到程序中的方法,我不想这样做。

任何建议,我怎么可以做到这一点。 谢谢。

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

例如,使用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);
   }
}

我不知道解决此问题的任何与操作系统无关的方法。

我相信您的问题可能在这里得到了回答: Java中活动其他进程的窗口

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

我能想到的唯一其他方法是调用应用程序,例如使用带有参数的chrome命令(如果需要的话)与

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();

在Linux上,尝试以下操作(这是kotlin代码):

val window = "The window name you want to show"
Runtime.getRuntime().exec(arrayOf("/bin/bash", "-c", "wmctrl -a \"$window\""))

在基础上工作(Loki)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM