另一种方法(对我们来说可靠)是创建 AutoIt 脚本,转换为 exe 文件并使用它,如下所示:
Java 代码:
// AutoIt script to set focus to file name field in browse window dialog
try {
Runtime.getRuntime().exec(ConfigProperties.getBaseDirectory() + "\\conf\\windows\\autoit\\SetFocusToFileNameField.exe");
} catch (IOException e) {
logger.info("Couldn't execute or set focus to file name field using AutoIt script: " + e.toString());
}
SleepUtil.sleepSmall();
// Imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
SleepUtil.sleepMedium();
} catch (AWTException e) {
e.printStackTrace();
}
// AutoIt script to click to open button to attach file
try {
Runtime.getRuntime().exec(ConfigProperties.getBaseDirectory() + "\\conf\\windows\\autoit\\ClickToOpenButton.exe");
SleepUtil.sleepLongMedium();
} catch (IOException e) {
logger.info("Couldn't click to open button to attach file using AutoIt script: " + e.toString());
}
ClickToOpenButton.au3:
; Click to Open button in File Explorer dialog
ClickToOpenButton()
Func ClickToOpenButton()
Local $windowHandle;
Local $windowTitle;
Local $openButton = "Button1";
If WinExists("File Upload") Then
$windowTitle = "File Upload";
Else
$windowTitle = "Open";
EndIf
$windowHandle = WinWait($windowTitle, "");
If Not WinActive($windowHandle) Then WinActivate($windowHandle);
ControlClick($windowHandle, "", $openButton);
; Local $openButtonHandle;
; Local $openButtonPosition;
; $openButtonHandle = ControlGetHandle($windowTitle, "", $openButton);
; $openButtonPosition = WinGetPos($openButtonHandle);
; MouseClick($MOUSE_CLICK_PRIMARY, $openButtonPosition[0]+20, $openButtonPosition[1]+10, 2);
EndFunc
SetFocusToFileNameField.au3:
; Set focus to file name field in File Explorer dialog
SetFocusToFileNameField()
Func SetFocusToFileNameField()
Local $windowHandle;
Local $windowTitle;
Local $windowField = "Edit1";
If WinExists("File Upload") Then
$windowTitle = "File Upload";
Else
$windowTitle = "Open";
EndIf
$windowHandle = WinWait($windowTitle, "");
If Not WinActive($windowHandle) Then WinActivate($windowHandle);
ControlSetText($windowHandle, "", "Edit1", "");
ControlFocus($windowTitle, "", $windowField);
EndFunc