Module: AutoItX3

Defined in:
lib/AutoItX3/au3.rb,
lib/AutoItX3/misc.rb,
lib/AutoItX3/mouse.rb,
lib/AutoItX3/window.rb,
lib/AutoItX3/control.rb,
lib/AutoItX3/filedir.rb,
lib/AutoItX3/graphic.rb,
lib/AutoItX3/process.rb,
lib/AutoItX3/keyboard.rb,
lib/AutoItX3/window/send_message.rb

Overview

This file is part of au3. Copyright © 2009, 2010 Marvin Gülker, Steven Heidel

au3 is published under the same terms as Ruby. See www.ruby-lang.org/en/LICENSE.txt

Defined Under Namespace

Classes: AU3_Function, Au3Error, Button, ComboBox, Control, Edit, ListBox, ListView, TabBook, TreeView, Window

Constant Summary collapse

INTDEFAULT =

The smallest value AutoIt can handle. Used for some parameter defaults.

-2147483647
VERSION =

The version of this au3 library.

"0.1.2"
BUFFER_SIZE =

This is the buffer size used for AutoItX3’s text “returning” functions. It will be subtracted by 1 due to the trailing 0 of wchar_t * type strings.

100_000
UNKNOWN_CURSOR =

Unknown cursor icon

0
APP_STARTING_CURSOR =

Application starting cursor (arrow with a hourglass next to it)

1
ARROW_CURSOR =

The normal cursor

2
CROSS_CURSOR =

Cross cursor

3
HELP_CURSOR =

Cursor with a question mark next to it

4
IBEAM_CURSOR =

Cursor for editing lines of text

5
ICON_CURSOR =
6
NO_CURSOR =

Cursor for forbidden actions (a circle with a strike through it)

7
SIZE_CURSOR =
8
SIZE_ALL_CURSOR =
9
SIZE_NESW_CURSOR =
10
SIZE_NS_CURSOR =
11
SIZE_NWSE_CURSOR =
12
SIZE_WE_CURSOR =
13
UP_ARROW_CURSOR =
14
WAIT_CURSOR =

Wait (the well-known “hourglass”)

15
IDLE_PRIORITY =

Lowest process priorety

0
SUBNORMAL_PRIORITY =

Subnormal process priority

1
NORMAL_PRIORITY =

Normal process priority

2
SUPNORMAL_PRIORITY =

Process priority above normal

3
HIGH_PRIORITY =

High process priority

4
REALTIME_PRIORITY =

Highest process priority. Use this with caution, it’s is the priority system processes run with.

5
LOGOFF =

Logs the currect user out

0
SHUTDOWN =

Shuts the computer down

1
REBOOT =

Reboot the computer

2
FORCE_CLOSE =

Force hanging applications to close

4
POWER_DOWN =

Turn the power off after shutting down (if the computer supports this)

8

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.optionsObject (readonly)

This hash is used for the #set_option method. Use the #set_option method to configure it.



144
145
146
# File 'lib/AutoItX3/au3.rb', line 144

def options
  @options
end

Class Method Details

.add_drive_map(device, remote_share, flags = 0, username = "", password = "") ⇒ Object

Maps a network drive.

Parameters

Every | is ment to be a backslash.

device

The device letter to map the drive to, in the form "X:". If this is an asterisk *, the next available letter will be used.

remote_share

The address of the network drive, in the form "||Server|Drive" or "||Server|Share".

flags

(0) A combination (via +) of 1 (PersistantMapping) and 8 (Show authentification dialog if neccessary).

username

(“”) The username, of the form "username" or "Domain|username".

password

(“”): The login password.

Return value

The assigned drive letter.

Raises

Au3Error

Failed to connect the network drive.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/AutoItX3/filedir.rb', line 24

def add_drive_map(device, remote_share, flags = 0, username = "", password = "")
  @functions[__method__] ||= AU3_Function.new("DriveMapAdd", 'SSLSSPI')
  buffer = " " * BUFFER_SIZE
  buffer.wide!
  @functions[__method__].call(device, remote_share, flags, username, password, buffer, buffer.size - 1)
  
  case last_error
    when 1 then raise(Au3Error, "Unknown error occured while mapping network drive!")
    when 2 then raise(Au3Error, "Access denied!")
    when 3 then raise(Au3Error, "Device '#{device}' is already assigned!")
    when 4 then raise(Au3Error, "Invalid device name '#{device}'!")
    when 5 then raise(Au3Error, "Invalid remote share '#{remote_share}'!")
    when 6 then raise(Au3Error, "The password is incorrect!")
    else return buffer.normal.strip
  end
end

.block_input=(val) ⇒ Object

Blocks user input.

Parameters

val

Wheather the user input should be blocked or not.

Return value

The passed argument, double-negated to ensure a boolean value.

Example

p AutoItX3.input_blocked? #=> false
AutoItX3.block_input = true
p AutoItX3.input_blocked? #=> true
AutoItX3.block_input = false
p AutoItX3.input_blocked? #=> false

Remarks

The user can gain back control by pressing [CTRL] + [ALT] + [DEL]. In older versions of Windows AutoIt itself may also be blocked.



26
27
28
29
30
# File 'lib/AutoItX3/misc.rb', line 26

def block_input=(val)
  @functions[__method__] ||= AU3_Function.new("BlockInput", 'L')
  @functions[__method__].call(!!val)
  @input_blocked = !!val
end

.cliptextObject

Reads the Windows clipboard.

Return value

The text saved in the clipboard, encoded in UTF-8.

Example

puts AutoItX3.cliptext #=> I love Ruby!

Remarks

Returns the text saved in the clipboard. It will be truncated at the AutoItX3::BUFFER_SIZE - 1th character or at a NUL character.

If the clipboard doesn’t contain text, this method returns an empty string.



117
118
119
120
121
122
123
# File 'lib/AutoItX3/misc.rb', line 117

def cliptext
  @functions[__method__] ||= AU3_Function.new("ClipGet", 'PL')
  cliptext = " " * BUFFER_SIZE
  cliptext.wide!
  @functions[__method__].call(cliptext, cliptext.size - 1)
  cliptext.normal.strip
end

.cliptext=(text) ⇒ Object

Writes text to the Windows clipboard.

Parameters

text

The text to write.

Return value

The argument passed.

Example

AutoItX3.cliptext = "I love Ruby!"
puts AutoItX3.cliptext #=> I love Ruby!

Remarks

You can’t write NUL characters to the clipboard, the text will be terminated.



101
102
103
104
105
# File 'lib/AutoItX3/misc.rb', line 101

def cliptext=(text)
  @functions[__method__] ||= AU3_Function.new("ClipPut", 'S')
  @functions[__method__].call(text.wide)
  text
end

.close_cd_tray(tray) ⇒ Object

Closes a CD/DVD drive.

Parameters

tray

The drive to close.

Return value

true on success, false otherwise.

Example

AutoItX3.open_cd_tray("E:")
AutoItX3.close_cd_tray("E:")

Remarks

The cd tray must be local at this computer, remote drives cannot be accessed. This method may return true if drive is a laptop drive which can only be closed manually.

Raises:

  • (ArgumentError)


74
75
76
77
78
# File 'lib/AutoItX3/misc.rb', line 74

def close_cd_tray(tray)
  @functions[__method__] ||= AU3_Function.new("CDTray", 'SS', 'L')
  raise(ArgumentError, "The drive name has to be of form 'X:'!") unless tray =~ /^\w:$/
  @functions[__method__].call(tray.wide, "closed".wide) == 1
end

.close_process(pid) ⇒ Object Also known as: kill_process

call-seq:

close_process(pid) ==> nil
kill_process(pid) ==> nil

Closes the given process.

Parameters

pid

The PID or name of the process to close.

Return value

nil.

Example

AutoItX3.close_process(1234)

Remarks

This method doesn’t ask the process to terminate nicely, it just kills it. If you’re familiar with Unix process signals, this method is nearer to sending SIGKILL than sending SIGTERM.



51
52
53
54
55
# File 'lib/AutoItX3/process.rb', line 51

def close_process(pid)
  @functions[__method__] ||= AU3_Function.new("ProcessClose", 'S', 'L')
  @functions[__method__].call(pid.to_s.wide)
  nil
end

.cursor_idObject

call-seq:

cursor_id ==> aFixnum
get_cursor_id ==> aFixnum

Get the cursor that is shown at the moment.

Return value

One of the *_CURSOR constants to indicate which cursor icon is actually shown.

Example

p AutoItX3.cursor_id #=> 5 #IBEAM_CURSOR, that one with the >I< form for editing texts.


117
118
119
120
# File 'lib/AutoItX3/mouse.rb', line 117

def cursor_id
  @functions[__method__] ||= AU3_Function.new("MouseGetCursor", '', 'L')
  @functions[__method__].call
end

.cursor_posObject

call-seq:

cursor_pos ==> anArray
get_cursor_pos ==> anArray

Returns the current cursor position.

Return value

The current cursor position in a two-element array of form [x, y].

Example

p AutoItX3.cursor_pos #=> [127, 345]


131
132
133
134
135
# File 'lib/AutoItX3/mouse.rb', line 131

def cursor_pos
  @functions[:cursor_pos_x] ||= AU3_Function.new("MouseGetPosX", 'V', 'L')
  @functions[:cursor_pos_y] ||= AU3_Function.new("MouseGetPosY", 'V', 'L')
  [@functions[:cursor_pos_x].call, @functions[:cursor_pos_y].call]
end

.delete_drive_map(device) ⇒ Object

Disconnects a network drive.

Parameters

device

The device to disconnect. Can be either of form "X:" or "||Server|share (| is a backslash).

Return value

nil.

Raises

Au3Error

Couldn’t disconnect the network drive.



48
49
50
51
52
53
54
55
# File 'lib/AutoItX3/filedir.rb', line 48

def delete_drive_map(device)
  @functions[__method__] ||= AU3_Function.new("DriveMapDel", 'S', 'L')
  result = @functions[__method__].call(device)
  if result == 0
    raise(Au3Error, "Failed to remove remote device '#{device}'!")
  end
  nil
end

.delete_ini_entry(filename, section, key) ⇒ Object

Deletes a key-value pair in a standard .ini file.

Parameters

filename

The filename of the file.

section

The section the key resides in.

key

The key to delete.

Return value

true on success, otherwise false.

Example

AutoItX3.delete_ini_entry("myini.ini", "mysection", "mykey")


85
86
87
88
89
90
91
92
# File 'lib/AutoItX3/filedir.rb', line 85

def delete_ini_entry(filename, section, key)
  @functions[__method__] ||= AU3_Function.new("IniDelete", 'SSS', 'L')
  if @functions[__method__].call(filename.wide, section.wide, key.wide) == 0
    false
  else
    true
  end
end

.drag_mouse(x1, y1, x2, y2, button = "Primary", speed = 10) ⇒ Object

Performes a drag & drop operation.

Parameters

x1

The start X coordinate.

y1

The start Y coordinate.

x2

The goal X coordinate.

y2

The goal Y coordinate.

button

The button to hold down while moving.

speed

The cursor’s speed. If 0, the cursor is set directly to the goal position.

Return value

nil.

Raises

Au3Error

Invalid mouse button specified.

Example

AutoItX3.drag_mouse(10, 10, 73, 86)
#With the secondary mouse button
AutoItX3.drag_mouse(10, 10, 73, 86, "Secondary")

Raises:



80
81
82
83
84
85
86
# File 'lib/AutoItX3/mouse.rb', line 80

def drag_mouse(x1, y1, x2, y2, button = "Primary", speed = 10)
  @functions[__method__] ||= AU3_Function.new("MouseClickDrag", 'SLLLLL', 'L')
  @functions[__method__].call(button.wide, x1, y1, x2, y2, speed)
  
  raise(Au3Error, "Invalid button '#{button}'!") if last_error == 1
  nil
end

.functionsObject

All yet assigned functions.



114
115
116
# File 'lib/AutoItX3/au3.rb', line 114

def self.functions
  @functions
end

.functions=(val) ⇒ Object

Reset all functions to the given hash.



119
120
121
# File 'lib/AutoItX3/au3.rb', line 119

def self.functions=(val)
  @functions = val
end

.get_drive_map(device) ⇒ Object

Gets the server of a network drive.

Parameters

device

The device to check.

Return value

A string of form "||Server|drive", where every | is meant to be a backslash.

Raises

Au3Error

Couldn’t retrieve the requested information.



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/AutoItX3/filedir.rb', line 64

def get_drive_map(device)
  @functions[__method__] ||= AU3_Function.new("DriveMapGet", 'SPI')
  buffer = " " * BUFFER_SIZE
  buffer.wide!
  ret = @functions[__method__].call(device, buffer, buffer.size - 1)
  
  if last_error == 1
    raise(Au3Error, "Failed to retrieve information about device '#{device}'")
  end
  buffer.normal.strip
end

.get_pixel_color(x, y, hex = false) ⇒ Object

Retrieves the color value of the pixel at the specified position.

Parameters

x

The pixel’s X coordinate.

y

The pixel’s Y coordinate.

hex

Changes the return value, see below.

Return value

The decimal color value of the specified pixel. If you set hex to true, you get a string in form #RRGGBB that describes the color in hexadecimal format.

Example

p AutoItX3.get_pixel_color(15, 15) #=> 1057590
p AutoItX3.get_pixel_color(15, 15, true) #=> "#102336"


47
48
49
50
51
52
# File 'lib/AutoItX3/graphic.rb', line 47

def get_pixel_color(x, y, hex = false)
  @functions[__method__] ||= AU3_Function.new("PixelGetColor", 'LL', 'L')
  res = @functions[__method__].call(x, y)
  return "#" + res.to_s(16).upcase if hex
  res
end

.hold_mouse_down(button = "Primary") ⇒ Object

call-seq:

hold_mouse_down( [ button = "Primary" ] ) ==> nil
mouse_down( [ button = "Primary" ] ) ==> nil

Holds a mouse button down.

Parameters

button

("Primary") The button to hold down.

Return value

nil.

Example

AutoItX3.hold_mouse_down("Primary")
AutoItX3.hold_mouse_down("Secondary")

Remarks

You should release the mouse button somewhen.



102
103
104
105
106
# File 'lib/AutoItX3/mouse.rb', line 102

def hold_mouse_down(button = "Primary")
  @functions[__method__] ||= AU3_Function.new("MouseDown", 'S')
  @functions[__method__].call(button.wide)
  nil
end

.input_blocked?Boolean

Returns wheather or not input is blocked by AutoItX3.

Return value

true or false.

Example

#See #block_input.

Remarks

This method fails to report that input has been enabled again if the user has pressed [CTRL] + [ALT] + [DEL] after a call to #block_input=.

Returns:

  • (Boolean)


40
41
42
# File 'lib/AutoItX3/misc.rb', line 40

def input_blocked?
  @input_blocked ||= false
end

.is_admin?Boolean

Determines wheather the current user has administrator privileges.

Return value

true or false,

Example

p AutoItX3.is_admin? #=> false

Returns:

  • (Boolean)


85
86
87
88
# File 'lib/AutoItX3/misc.rb', line 85

def is_admin?
  @functions[__method__] ||= AU3_Function.new("IsAdmin", 'V', 'L')
  @functions[__method__].call == 1
end

.last_errorObject

Returns the error code of the last called AutoItX3 function, which is 0 if everything worked fine.



148
149
150
151
# File 'lib/AutoItX3/au3.rb', line 148

def last_error
  @functions[__method__] ||= AU3_Function.new("error", '', 'L')
  @functions[__method__].call
end

.method_missing(sym, *args, &block) ⇒ Object

Allows you to do things like

AutoItX3.ctrl_c

.Every _ will be used to separate a key press from another, so you can’t send _ with this function. Possible shortcuts are:

  • ctrl

  • shift

  • alt

  • win

  • enter (or return)

  • del

This text sequences can’t be sent, too.



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/AutoItX3/keyboard.rb', line 189

def method_missing(sym, *args, &block)
  super if !args.empty? or block
  cmds = sym.to_s.split("_")
  callsequence = ""
  cmds.each do |cmd|
    callsequence << case cmd.downcase
      when "ctrl" then "^"
      when "shift" then "+"
      when "alt" then "!"
      when "win" then "#"
      when "enter" then "{ENTER}"
      when "return" then "{ENTER}"
      when "del" then "{DEL}"
      else
        cmd
    end
  end
  send_keys(callsequence)
end

.mouse_click(x = INTDEFAULT, y = INTDEFAULT, button = "Primary", clicks = 1, speed = 10) ⇒ Object

Executes a mouse click.

Parameters

  • x (INTDEFAULT): The X position. The cursor’s current X if not specified.

  • y (INTDEFAULT): The Y position. The cursor’s current Y if not specified.

  • button("Primary"): The mouse button to click width. On a mouse for left-handed people the right, for right-handed people the left mouse button.

  • clicks(1): The number of times to click.

  • speed(10): The speed the mouse cursor will move with. If set to 0, the cursor is set immediatly.

Return value

nil.

Raises

Au3Error

Invalid mouse button specified.

Example

#Normal mouse click at (100|100). 
AutoItX3.mouse_click(100, 100)
#Click with the right (or left if buttons are swapped) button
AutoItX3.mouse_click(AutoItX3::INTDEFAULT, AutoItX3::INTDEFAULT, "Secondary")
#Don't move the cursor
AutoItX3.mouse_click(100, 100, "Primary", 1, 0)

Clicks the mouse.

Raises:



56
57
58
59
60
61
62
# File 'lib/AutoItX3/mouse.rb', line 56

def mouse_click(x = INTDEFAULT, y = INTDEFAULT, button = "Primary", clicks = 1, speed = 10)
  @functions[__method__] ||= AU3_Function.new("MouseClick", 'SLLLL', 'L')
  @functions[__method__].call(button.wide, x, y, clicks, speed)
  
  raise(Au3Error, "Invalid button '#{button}'!") if last_error == 1
  nil
end

.mouse_wheel(direction, times = 5) ⇒ Object

Scrolls up or down the mouse wheel.

Parameters

direction

The scrolling direction, either "up or "down.

times

The scrolling steps. These are not full wheel turns.

Return value

nil.

Example

#5 steps up. 
AutoItX3.mouse_wheel("up")
#3 steps down. 
AutoItX3.mouse_wheel("down", 3)

Raises:



186
187
188
189
190
191
192
# File 'lib/AutoItX3/mouse.rb', line 186

def mouse_wheel(direction, times = 5)
  @functions[__method__] ||= AU3_Function.new("MouseWheel", 'SL')
  @functions[__method__].call(direction.wide, times)
  
  raise(Au3Error, "Undefined mouse wheel direction '#{direction}!") if last_error == 1
  nil
end

.move_mouse(x, y, speed = 10) ⇒ Object

call-seq:

move_mouse( x , y [, speed = 10 ] ) ==> nil
mouse_move( x , y [, speed = 10 ] ) ==> nil

Moves the mouse cursor to the given position.

Parameters

x

The goal X coordinate.

y

The goal Y coordinate.

speed

(10) The speed to move the cursor with. 0 means no movement and the cursor is set directly to the goal position.

Return value

nil.



148
149
150
151
152
# File 'lib/AutoItX3/mouse.rb', line 148

def move_mouse(x, y, speed = 10)
  @functions[__method__] ||= AU3_Function.new("MouseMove", 'LLL', 'L')
  @functions[__method__].call(x, y, speed)
  nil
end

.msleep(msecs) ⇒ Object

Wait for the specified amount of milliseconds.

Return value

nil.

Remarks

In AutoIt, this function is named “Sleep”, but to avoid compatibility issues with Ruby’s own sleep I decided to name the function “msleep” (the “m” indicates “milli”). If you wish to name it “sleep”, simply define an alias.



155
156
157
158
# File 'lib/AutoItX3/misc.rb', line 155

def msleep(msecs)
  @functions[__method__] ||= AU3_Function.new("Sleep", 'L')
  @functions[__method__].call(msecs)
end

.open_cd_tray(tray) ⇒ Object

Opens a CD/DVD drive.

Parameters

tray

The drive to eject, a string of form "X:".

Return value

true on success, false otherwise.

Example

AutoItX3.open_cd_tray("E:") #| true
AutoItX3.open_cd_tray("Y:") #| false

Remarks

The cd tray must be local at this computer, remote drives cannot be accessed.

Raises:

  • (ArgumentError)


55
56
57
58
59
# File 'lib/AutoItX3/misc.rb', line 55

def open_cd_tray(tray)
  @functions[__method__] ||= AU3_Function.new("CDTray", 'SS', 'L')
  raise(ArgumentError, "The drive name has to be of form 'X:'!") unless tray =~ /^\w:$/
  @functions[__method__].call(tray.wide, "open".wide) == 1
end

.pixel_checksum(x1, y1, x2, y2, step = 1) ⇒ Object

Computes a checksum of the pixels in the specified region.

Parameters

x1

Upper-left X-Coordinate of the region.

y1

Upper-left Y-Coordinate of the region.

x2

Lower-right X-Coordinate of the region.

y2

Lower-right Y-Coordinate of the region.

step

(1) Indicatates how many pixels are used for the computation. Every step-th pixel will be checked.

Return value

The computed checksum.

Example

#Compute the checksum of [0, 0, 100, 100]
p AutoItX3.pixel_checksum(0, 0, 100, 100) #=> 2252979179
#Then move a window into this region. 
p AutoItX3.pixel_checksum(0, 0, 100, 100) #=> 4287194203

Remarks

If the checksum changes, that only indidcates that something has changed, not what. Note that this method may be very time-consuming, so think about increasing the step parameter (but bear in mind that that will generate more inaccurate checksums).



30
31
32
33
# File 'lib/AutoItX3/graphic.rb', line 30

def pixel_checksum(x1, y1, x2, y2, step = 1)
  @functions[__method__] ||= AU3_Function.new("PixelChecksum", 'LLLLL', 'L')
  @functions[__method__].call(x1, y1, x2, y2, step)
end

.process_exists?(pid) ⇒ Boolean

Checks wheather or not the given name or PID exists.

Parameters

pid

The PID or name of the process to check.

Return value

false if the process doesn’t exist, otherwise the PID of the process.

Example

p AutoItX3.process_exists?(1234) #=> false
p AutoItX3.process_exists("ruby.exe") #=> 4084

Returns:

  • (Boolean)


66
67
68
69
70
# File 'lib/AutoItX3/process.rb', line 66

def process_exists?(pid)
  @functions[__method__] ||= AU3_Function.new("ProcessExists", 'S', 'L')
  pid = @functions[__method__].call(pid.to_s.wide)
  pid > 0 && pid
end

.read_ini_entry(filename, section, key, default = "") ⇒ Object

Reads a value from a standard .ini file.

Parameters

filename

The filename of the file.

section

The section the key resides in.

key

The key to read.

default

(“”)A string to return on failure.

Return value

The value of the default parameter.

Example

puts AutoItX3.read_ini_entry("myini.ini", "mysection", "mykey") #=> myvalue
#Nonexistant key: 
puts AutoItX3.read_ini_entry("myini.ini", "mysection", "mynonexsistingkey") #=> 
#With default value
puts AutoItX3.read_ini_entry("myini,ini", "mysection", "mynonexsistingkey", "NOTHING") #=> NOTHING

Remarks

The returned string has a maximum length of AutoItX3::BUFFER_SIZE - 1 characters.



110
111
112
113
114
115
116
# File 'lib/AutoItX3/filedir.rb', line 110

def read_ini_entry(filename, section, key, default = "")
  @functions[__method__] ||= AU3_Function.new("IniRead", 'SSSSPI')
  buffer = " " * BUFFER_SIZE
  buffer.wide!
  @functions[__method__].call(filename.wide, section.wide, key.wide, default.to_s.wide, buffer, buffer.size - 1)
  buffer.normal.strip
end

.release_mouse(button = "Primary") ⇒ Object

call-seq:

release_mouse( [ button = "Primary" ] ) ==> nil
mouse_up( [ button = "Primary" ] ) ==> nil

Releases a mouse button hold down by #hold_mouse_down.

Parameters

button

("Primary") The mouse button to release.

Return value

nil.

Example

AutoItX3.hold_mouse_down
AutoItX3.release_mouse
#With the secondary button
AutoItX3.hold_mouse_down("Secondary")
AutoItX3.release_mouse("Secondary")


169
170
171
172
173
# File 'lib/AutoItX3/mouse.rb', line 169

def release_mouse(button = "Primary")
  @functions[__method__] ||= AU3_Function.new("MouseUp", 'S')
  @functions[__method__].call(button.wide)
  nil
end

.run(name, workingdir = "", flag = 1) ⇒ Object

Runs a program.

Parameters

name

The command to run.

workingdir

("") The working directory to start the process in. Default is the current one.

flag

(1) Additional properties you want to set on the window. Possible value include SW_HIDE, SW_MINIMIZE and SW_MAXIMIZE, which are defined as constants of the Window class. Default is to set nothing.

Return value

The PID of the newly created process.

Raises

Au3Error

Couldn’t awake the specified program.

Example

p AutoItX3.run("notepad.exe") #=> 502

Remarks

The program flow continues; if you want to wait for the process to finish, use #run_and_wait.

Raises:



147
148
149
150
151
152
# File 'lib/AutoItX3/process.rb', line 147

def run(name, workingdir = "", flag = 1)
  @functions[__method__] ||= AU3_Function.new("Run", 'SSL', 'L')
  pid = @functions[__method__].call(name.wide, workingdir.wide, flag)
  raise(Au3Error, "An error occured while starting process '#{name}'!") if last_error == 1
  pid
end

.run_and_wait(name, workingdir = "", flag = 1) ⇒ Object

Runs a program and waits until the process has finished.

Parameters

name

The command to run.

workingdir

("") The working directory to start the process in. Default is the current one.

flag

(1) Additional properties you want to set on the window. Possible value include SW_HIDE, SW_MINIMIZE and SW_MAXIMIZE, which are defined as constants of the Window class. Default is to set nothing.

Return value

The exitcode of the process.

Raises

Au3Error

Couldn’t awake the specified program.

Example

AutoItX3.run_and_wait("ipconfig") #| 0
AutoItX3.run_and_wait("nonexistant.exe")

Remarks

If you don’t want to wait until the program has finished, use #run.

This method doesn’t do anything different from Ruby’s own Kernel#system method beside the flag you can pass to GUI applications.

Raises:



171
172
173
174
175
176
# File 'lib/AutoItX3/process.rb', line 171

def run_and_wait(name, workingdir = "", flag = 1)
  @functions[__method__] ||= AU3_Function.new("RunWait", 'SSL', 'L')
  exitcode = @functions[__method__].call(name.wide, workingdir.wide, flag)
  raise(Au3Error, "An error occured while starting process '#{name}'!") if last_error == 1
  exitcode
end

.run_as_set(username, domain, password, options = 1) ⇒ Object

Changes the the owner of following #run and #run_and_wait methods to the given user.

Parameters

username

The name of the user you want to run commands as.

domain

The user’s domain.

password

The user’s password.

options

(1) One of the following: 0: don’t load the user profile, 1 (default): load the user profile, 2: Only for networking.

Return value

nil.

Raises

NotImplementedError

You’re using Windows ME or earlier which don’t support this method.

Example

AutoItX3.run_as_set("Rubyist", "WORKGROUP", "MyFamousUncrackablePassword")
AutoItX3.run("hack_them_all.exe")


192
193
194
195
196
197
198
# File 'lib/AutoItX3/process.rb', line 192

def run_as_set(username, domain, password, options = 1)
  @functions[__method__] ||= AU3_Function.new("RunAsSet", 'SSSI', 'L')
  if @functions[__method__].call(username.wide, domain.wide, password.wide, options) == 0
    raise(NotImplementedError, "Your system does not support the #run_as_set method.")
  end
  nil
end

.send_keys(keys, flag = false) ⇒ Object

Simulates keyboard input.

Parameters

keys

The keystrokes to simulate. See Remarks.

flag

(false) If set to true, escape sequences in braces { and } are ignored.

Return value

nil.

Example

#Simulate [SHIFT] + [A], [B] and [C]. 
AutoItX3.send_keys("Abc")
#Simulate [A], [ESC] and b. 
AutoItX3.send_keys("a{ESC}b")
#Ignore the escape sequence and send it as regular keystrokes. 
AutoItX3.send_keys("a{ESC}b", true)
#Sends [ALT] + [F]
AutoItX3.send_keys("!F")

Remarks

You may use some of the follwing escape sequences in braces { and } (copied from the AutoItX3 help):

Escape sequence     | Resulting keypress
====================+============================================================
!                   | !
--------------------+------------------------------------------------------------
#                   | #
--------------------+------------------------------------------------------------
+                   | +
--------------------+------------------------------------------------------------
^                   | ^
--------------------+------------------------------------------------------------
{                   | {
--------------------+------------------------------------------------------------
}                   | }
--------------------+------------------------------------------------------------
SPACE               | SPACE
--------------------+------------------------------------------------------------
ENTER               | Return on the main keyboard
--------------------+------------------------------------------------------------
ALT                 | Alt
--------------------+------------------------------------------------------------
BACKSPACE or BS     | Backspace
--------------------+------------------------------------------------------------
DELETE or DEL       | Del
--------------------+------------------------------------------------------------
UP                  | Up arrow
--------------------+------------------------------------------------------------
DOWN                | Down arrow
--------------------+------------------------------------------------------------
LEFT                | Left arrow
--------------------+------------------------------------------------------------
RIGHT               | Right arrow
--------------------+------------------------------------------------------------
HOME                | Home
--------------------+------------------------------------------------------------
END                 | End
--------------------+------------------------------------------------------------
ESCAPE or ESC       | ESC
--------------------+------------------------------------------------------------
INSERT or INS       | Ins
--------------------+------------------------------------------------------------
PGUP                | Page Up
--------------------+------------------------------------------------------------
PGDN                | Page Down
--------------------+------------------------------------------------------------
F1 - F12            | Function keys 1 to 12
--------------------+------------------------------------------------------------
TAB                 | Tab
--------------------+------------------------------------------------------------
PRINTSCREEN         | Printscreen
--------------------+------------------------------------------------------------
LWIN                | Left Windows key
--------------------+------------------------------------------------------------
RWIN                | Right Windows key
--------------------+------------------------------------------------------------
NUMLOCK on          | NumLock on
--------------------+------------------------------------------------------------
CAPSLOCK off        | CapsLock off
--------------------+------------------------------------------------------------
SCROLLLOCK toggle   | ScrollLock toggle
--------------------+------------------------------------------------------------
BREAK               | For CTRL-Break processing
--------------------+------------------------------------------------------------
PAUSE               | Pause
--------------------+------------------------------------------------------------
NUMPAD0 - NUMPAD9   | Numpad number keys. 
--------------------+------------------------------------------------------------
NUMPADMUTLT         | Numpad Multipy
--------------------+------------------------------------------------------------
NUMPADADD           | Numpad Add
--------------------+------------------------------------------------------------
NUMPADSUBT          | Numpad Subtract
--------------------+------------------------------------------------------------
NUMPADDIV           | Numpad Division
--------------------+------------------------------------------------------------
NUMPADDOT           | Numpad dot
--------------------+------------------------------------------------------------
NUMPADENTER         | Numpad return key
--------------------+------------------------------------------------------------
APPSKEY             | Windows App key
--------------------+------------------------------------------------------------
LALT                | Left Alt key
--------------------+------------------------------------------------------------
RALT                | Right Alt key
--------------------+------------------------------------------------------------
LCTRL               | Left control key
--------------------+------------------------------------------------------------
LSHIFT              | Left Shift key
--------------------+------------------------------------------------------------
RSHIFT              | Right Shift key
--------------------+------------------------------------------------------------
SLEEP               | Computer Sleep key
--------------------+------------------------------------------------------------
ALTDOWN             | Hold Alt down until ALTUP is sent
--------------------+------------------------------------------------------------
SHIFTDOWN           | Hold Shift down until SHIFTUP is sent
--------------------+------------------------------------------------------------
CTRLDOWN            | Hold CTRL down until CTRLUP is sent
--------------------+------------------------------------------------------------
LWINDOWN            | Hold the left Windows key down until LWDINUP is sent
--------------------+------------------------------------------------------------
RWINDOWN            | Hold the right Windows key down until RWINUP is sent
--------------------+------------------------------------------------------------
ASC nnnn            | Send the kombination Alt+nnnn on numpad
--------------------+------------------------------------------------------------
BROWSER_BACK        | 2000/XP Only: Select the browser "back" button
--------------------+------------------------------------------------------------
BROWSER_FORWARD     | 2000/XP Only: Select the browser "forward" button
--------------------+------------------------------------------------------------
BROWSER_REFRESH     | 2000/XP Only: Select the browser "refresh" button
--------------------+------------------------------------------------------------
BROWSER_STOP        | 2000/XP Only: Select the browser "stop" button
--------------------+------------------------------------------------------------
BROWSER_SEARCH      | 2000/XP Only: Select the browser "search" button
--------------------+------------------------------------------------------------
BROWSER_FAVORITES   | 2000/XP Only: Select the browser "favorites" button
--------------------+------------------------------------------------------------
BROWSER_HOME        | 2000/XP Only: Launch the browser and go to the home page
--------------------+------------------------------------------------------------
VOLUME_MUTE         | 2000/XP Only: Mute the volume
--------------------+------------------------------------------------------------
VOLUME_DOWN         | 2000/XP Only: Reduce the volume
--------------------+------------------------------------------------------------
VOLUME_UP           | 2000/XP Only: Increase the volume
--------------------+------------------------------------------------------------
MEDIA_NEXT          | 2000/XP Only: Select next track in media player
--------------------+------------------------------------------------------------
MEDIA_PREV          | 2000/XP Only: Select previous track in media player
--------------------+------------------------------------------------------------
MEDIA_STOP          | 2000/XP Only: Stop media player
--------------------+------------------------------------------------------------
MEDIA_PLAY_PAUSE    | 2000/XP Only: Play/pause media player
--------------------+------------------------------------------------------------
LAUNCH_MAIL         | 2000/XP Only: Launch the email application
--------------------+------------------------------------------------------------
LAUNCH_MEDIA        | 2000/XP Only: Launch media player
--------------------+------------------------------------------------------------
LAUNCH_APP1         | 2000/XP Only: Launch user app1
--------------------+------------------------------------------------------------
LAUNCH_APP2         | 2000/XP Only: Launch user app2

A “!” in keys indicates an ALT keystroke, the “+” means SHIFT, “^” CTRL and “#” is the Windows key.



173
174
175
176
# File 'lib/AutoItX3/keyboard.rb', line 173

def send_keys(keys, flag = false)
  @functions[__method__] ||= AU3_Function.new("Send", 'SL')
  @functions[__method__].call(keys.wide, flag)
end

.set_option(option, value) ⇒ Object Also known as: opt

call-seq:

set_option( option , value ) ==> anInteger
set_option( option , value) {...} ==> anObject
opt( option , value ) ==> anInteger
opt( option , value ) {...} ==> anObject

Sets an option that changes the behaviour of AutoIt. If you choose the block form, the option will be resetted after the block finished. The block form returns the last expression, the normal form the previously set option.

The following options are possible (copied from the AutoItX3 help file):

Option              | Description
====================+============================================================
CaretCoordMode      | Sets the way coords are used in the caret functions, 
                    | either absolute coords or coords relative to the current 
                    | active window:
                    | 0 = relative coords to the active window
                    | 1 = absolute screen coordinates (default)
                    | 2 = relative coords to the client area of the active window
--------------------+------------------------------------------------------------
ColorMode           | Sets the way colors are defined, either RGB or BGR. RGB is 
                    | the default but in previous versions of AutoIt (pre 3.0.102) 
                    | BGR was the default:
                    | 0 = Colors are defined as RGB (0xRRGGBB) (default)
                    | 1 = Colors are defined as BGR (0xBBGGRR) (the mode used in 
                    |     older versions of AutoIt)
--------------------+------------------------------------------------------------
MouseClickDelay     | Alters the length of the brief pause in between mouse 
                    | clicks. 
                    | Time in milliseconds to pause (default=10). 
--------------------+------------------------------------------------------------
MouseClickDownDelay | Alters the length a click is held down before release. 
                    | Time in milliseconds to pause (default=10). 
--------------------+------------------------------------------------------------
MouseClickDragDelay | Alters the length of the brief pause at the start and 
                    | end of a mouse drag operation. 
                    | Time in milliseconds to pause (default=250). 
--------------------+------------------------------------------------------------
MouseCoordMode      | Sets the way coords are used in the mouse functions, 
                    | either absolute coords or coords relative to the current 
                    | active window: 
                    | 0 = relative coords to the active window
                    | 1 = absolute screen coordinates (default)
                    | 2 = relative coords to the client area of the active window
--------------------+------------------------------------------------------------
PixelCoordMode      | Sets the way coords are used in the pixel functions, 
                    | either absolute coords or coords relative to the current 
                    | active window:
                    | 0 = relative coords to the active window
                    | 1 = absolute screen coordinates (default)
                    | 2 = relative coords to the client area of the active window
--------------------+------------------------------------------------------------
SendAttachMode      | Specifies if AutoIt attaches input threads when using then 
                    | Send() function. When not attaching (default mode=0) 
                    | detecting the state of capslock/scrolllock and numlock 
                    | can be unreliable under NT4. However, when you specify 
                    | attach mode=1 the Send("{... down/up}") syntax will not 
                    | work and there may be problems with sending keys to "hung" 
                    | windows. ControlSend() ALWAYS attaches and is not affected 
                    | by this mode. 
                    | 0 = don't attach (default)
                    | 1 = attach
--------------------+------------------------------------------------------------
SendCapslockMode    | Specifies if AutoIt should store the state of capslock 
                    | before a Send function and restore it afterwards. 
                    | 0 = don't store/restore
                    | 1 = store and restore (default)
--------------------+------------------------------------------------------------
SendKeyDelay        | Alters the the length of the brief pause in between 
                    | sent keystrokes. 
                    | Time in milliseconds to pause (default=5). Sometimes a 
                    | value of 0 does not work; use 1 instead.
--------------------+------------------------------------------------------------
SendKeyDownDelay    | Alters the length of time a key is held down before 
                    | released during a keystroke. For applications that 
                    | take a while to register keypresses (and many games) 
                    | you may need to raise this value from the default. 
                    | Time in milliseconds to pause (default=1).
--------------------+------------------------------------------------------------
WinDetectHiddenText | Specifies if hidden window text can be "seen" by the 
                    | window matching functions. 
                    | 0 = Do not detect hidden text (default)
                    | 1 = Detect hidden text
--------------------+------------------------------------------------------------
WinSearchChildren   | Allows the window search routines to search child windows 
                    | as well as top-level windows. 
                    | 0 = Only search top-level windows (default)
                    | 1 = Search top-level and child windows
--------------------+------------------------------------------------------------
WinTextMatchMode    | Alters the method that is used to match window text 
                    | during search operations. 
                    | 1 = Complete / Slow mode (default)
                    | 2 = Quick mode
                    | In quick mode AutoIt can usually only "see" dialog text, 
                    | button text and the captions of some controls. In the 
                    | default mode much more text can be seen (for instance the 
                    | contents of the Notepad window). 
                    | If you are having performance problems when performing 
                    | many window searches then changing to the "quick" mode may 
                    | help. 
--------------------+------------------------------------------------------------
WinTitleMatchMode   | Alters the method that is used to match window titles 
                    | during search operations. 
                    | 1 = Match the title from the start (default)
                    | 2 = Match any substring in the title
                    | 3 = Exact title match
                    | 4 = Advanced mode, see the AutoItX3 help. 
--------------------+------------------------------------------------------------
WinWaitDelay        | Alters how long a script should briefly pause after a 
                    | successful window-related operation. 
                    | Time in milliseconds to pause (default=250).

Raises:

  • (ArgumentError)


264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/AutoItX3/au3.rb', line 264

def set_option(option, value)
  raise(ArgumentError, "Unknown option '#{option}'!") unless @options.include? option
  @functions[__method__] ||= AU3_Function.new("AutoItSetOption", 'PL', 'L')
  if block_given?
    previous = @options[option]
    @functions[__method__].call(option.to_wchar_t, value)
    ret = yield
    @functions[__method__].call(option.to_wchar_t, previous)
  else
    ret = @functions[__method__].call(option.to_wchar_t, value)
    @options[option] = ret
  end
  ret
end

.set_process_priority(pid, priority) ⇒ Object

Sets a process’s priority.

Parameters

pid

The PID or name of the process whose priority you want to change.

priority

One of the *_PRIORITY constants.

Return value

The argument passed as priority.

Raises

Au3Error

You passed an invalid priority value or some other error occured.

Example

AutoItX3.set_process_priority(4084, AutoItX3::HIGH_PRIORITY)
AutoItX3.set_process_priority("ruby.exe", AutoItX3::SUBNORMAL_PRIORITY)

Remarks

You shouldn’t set a process’s priority to REALTIME_PRIORITY, since that is the priority system processes run with which are likely more important than your process. The same goes the other way round: Don’t decrease a system process’s priority.



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/AutoItX3/process.rb', line 87

def set_process_priority(pid, priority)
  @functions[__method__] ||= AU3_Function.new("ProcessSetPriority", 'SL', 'L')
  @functions[__method__].call(pid.to_s.wide, priority)
  
  case last_error
    when 1 then raise(Au3Error, "Unknown error occured when trying to set process priority of '#{pid}'!")
    when 2 then raise(Au3Error, "Unsupported priority '#{priority}'!")
    else
      return priority
  end
end

.shutdown(code) ⇒ Object

Shuts down or reboots your computer, or logs you off.

Parameters

code

One of the following constants: SHUTDOWN, REBOOT, LOGOFF. You may combine (by using addition with +) each of them with FORCE_CLOSE which forces all hanging applications to close. Additionally, you may combine SHUTDOWN with POWEROFF which ensures that your computer gets cut off from the power supply.

Return value

Unknown.

Example

AutoItX3.shutdown(AutoItX3::LOGOFF | AutoItX3::FORCE_CLOSE)
AutoItX3.shutdown(AutoItX3::REBOOT)
AutoItX3.shutdown(AutoItX3::SHUTDOWN + AutoItX3::FORCE_CLOSE + AutoItX3::POWEROFF)
#If your computer is still running after executing this sequence of commands, you may should check your hardware.


210
211
212
213
# File 'lib/AutoItX3/process.rb', line 210

def shutdown(code)
  @functions[__method__] ||= AU3_Function.new("Shutdown", 'L', 'L')
  @functions[__method__].call(code) == 1
end

.tool_tip(text, x = INTDEFAULT, y = INTDEFAULT) ⇒ Object Also known as: tooltip

call-seq:

tool_tip( text [, x = INTDEFAULT [, y = INTDEFAULT ] ] ) ==> nil
tooltip( text [, x = INTDEFAULT [, y = INTDEFAULT ] ] ) ==> nil

Displays a tooltip at the given position.

Parameters

text

The text to display.

x

(INTDEFAULT) The X coordinate where to display the tooltip. Defaults to the cursor’s X coordinate if ommited.

y

(INTDEFAULT) The Y coordinate where to display the tooltip. Defaults to the cursor’s Y coordinate if ommited.

Return value

nil.

Remarks

Coordinates out of range are automatically corrected.

The tooltip will be deleted when the program ends, or after a system-dependent timeout.



141
142
143
144
# File 'lib/AutoItX3/misc.rb', line 141

def tool_tip(text, x = INTDEFAULT, y = INTDEFAULT)
  @functions[__method__] ||= AU3_Function.new("ToolTip", 'SLL')
  @functions[__method__].call(text.wide, x, y)
end

.wait_for_process(procname, timeout = 0) ⇒ Object

Waits for the given process name to exist.

Parameters

procname

The name of the process to wait for.

timeout

(0) The time to wait, in seconds. The default is to wait infinitely.

Return value

true if the process was found, false if timeout was reached.

Example

AutoItX3.wait_for_process("nonexistant.exe", 2) #| false
AutoItX3.wait_for_process("ruby.exe") #| true

Remarks

This is the only process-related method that doesn’t take a PID, because to wait for a special PID doesn’t make sense, since PIDs are generated randomly.



112
113
114
115
# File 'lib/AutoItX3/process.rb', line 112

def wait_for_process(procname, timeout = 0)
  @functions[__method__] ||= AU3_Function.new("ProcessWait", 'SL', 'L')
  @functions[__method__].call(procname.to_s.wide, timeout) == 1
end

.wait_for_process_close(pid, timeout = 0) ⇒ Object

Waits for the given process name or PID to disappear.

Parameters

pid

The PID or process name to wait for.

timeout

The time to wait, in seconds. 0 means to wait infinitely, which is the default.

Return value

true if the process disappeared, false if timeout was reached.

Example

AutoItX3.wait_for_process_close(4084) #| true
AutoItX3.wait_for_process_close("ruby.exe", 1) #| false
#Attention on this one: 
AutoItX3.wait_for_process_close("nonexistant.exe") #| true


128
129
130
131
# File 'lib/AutoItX3/process.rb', line 128

def wait_for_process_close(pid, timeout = 0)
  @functions[__method__] ||= AU3_Function.new("ProcessWaitClose", 'SL', 'L')
  @functions[__method__].call(pid.to_s.wide, timeout) == 1
end

.write_ini_entry(filename, section, key_value, value) ⇒ Object

Writes the specified key-value pair in a .ini file.

Parameters

filename

The file’s filename.

section

The section you want to write in.

key

The key whose value you want to write.

value

The value to write.

Return value

The value argument.

Raises

Au3Error

filename is read-only.

Example

AutoItX3.write_ini_entry("minini.ini", "mysection", "mykey", "myvalue")

Remarks

Both the section and the key will be created if they aren’t there already. Likewise is the file if nonexistant.

If the specified key-value pair already exists, it will be overwritten.



134
135
136
137
138
139
140
141
142
# File 'lib/AutoItX3/filedir.rb', line 134

def write_ini_entry(filename, section, key_value, value)
  @functions[__method__] ||= AU3_Function.new("IniWrite", 'SSSS', 'L')
  
  if @functions[__method__].call(filename.wide, section.wide, key_value.wide, value.wide) == 0
    raise(Au3Error, "Cannot open file for write access!")
  else
    value
  end
end