Class: Win32::Activate

Inherits:
Object
  • Object
show all
Defined in:
lib/win32/activate.rb,
lib/win32/activate/version.rb

Constant Summary collapse

GetWindowThreadProcessId =

windows api GetWindowThreadProcessId

Win32::API.new('GetWindowThreadProcessId', 'LP', 'L', 'user32')
EnumWindows =

windows api EnumWindows

Win32::API.new('EnumWindows', 'KP', 'L', 'user32')
VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.active(pid = nil) ⇒ Object

Do window activate by process id. If pid is nil, activate window by current process id.



9
10
11
# File 'lib/win32/activate.rb', line 9

def self.active(pid=nil)
	self.new.activate_process_window( pid || Process.pid )
end

Instance Method Details

#activate_process_window(pid) ⇒ Object

Find parent process that has window handler, and set window activa ( by WSH )



62
63
64
65
# File 'lib/win32/activate.rb', line 62

def activate_process_window( pid )
  pid , hwnd = find_parent_process_with_hwnd(pid)
  wsh.AppActivate(pid) if pid
end

#create_pid_to_hwnd_dicObject

Create dictionay of { pid => hwnd }



13
14
15
16
17
18
19
20
21
# File 'lib/win32/activate.rb', line 13

def create_pid_to_hwnd_dic
  dic = {}
  EnumWindows.call( Win32::API::Callback.new('LP', 'I'){ |handle, param| 
   pid=[0].pack('L');
   GetWindowThreadProcessId.call(handle, pid);
   dic[pid.unpack('L')[0]] = handle
  }, nil )
  dic
end

#find_parent_pid(pid) ⇒ Object

Find parent process id ( by WMI )



42
43
44
45
46
47
48
# File 'lib/win32/activate.rb', line 42

def find_parent_pid pid
  ppid = nil
  wmi.ExecQuery("SELECT * FROM Win32_Process WHERE ProcessID=#{pid}").each{|i|
    ppid = i.ParentProcessID
  }
  return ppid
end

#find_parent_process_with_hwnd(pid) ⇒ Object

Find process id and window handler. If process has not window handler, find parent process, parent’s parent process … If result of search parent process reach to nil, then return nil



53
54
55
56
57
58
59
# File 'lib/win32/activate.rb', line 53

def find_parent_process_with_hwnd pid
  while hwnd=pid_to_hwnd[pid].nil?
    pid = find_parent_pid(pid)
    return nil unless pid
  end
  return [pid,hwnd]
end

#pid_to_hwndObject

Convert pid to window handler. if process not has window, return nil



24
25
26
27
# File 'lib/win32/activate.rb', line 24

def pid_to_hwnd
  @pid_to_hwnd = create_pid_to_hwnd_dic unless @pid_to_hwnd
  @pid_to_hwnd
end

#wmiObject

Windows Management Instrumentation Object (OLE)



30
31
32
33
# File 'lib/win32/activate.rb', line 30

def wmi
  @wmi ||= WIN32OLE.connect("winmgmts:root/CIMV2")
  @wmi
end

#wshObject

Windows Scripting Host (OLE)



36
37
38
39
# File 'lib/win32/activate.rb', line 36

def wsh
  @wsh ||= WIN32OLE.new('Wscript.Shell')
  @wsh
end