![](/img/trans.png)
[英]How to switch between windows in Chrome using Selenium WebDriver with Java?
[英]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.