Ruby Programming Examples: Email, Encryption, Zip, HTTP, XML, FTP

Chilkat Software Components

Restrict Ruby Script to One Running Instance

Back

Question:
How do I restrict a Ruby script to a single running instance on a Windows system? In other words, if a script is already running, and the same script is started again, we want to prevent it.

Answer:
See code below:

require 'Win32API'


SW_HIDE = 0
WS_OVERLAPPED = 0
WS_DISABLED = 0x08000000
WS_MINIMIZED = 0x20000000


 def already_running
   #
   # Not sure of any other way to do this.
   # Create a window with the title "i4FileProcessorHiddenWindow".
When we come to run this program again,
   # if there is already a window called
"i4FileProcessorHiddenWindow" then abort that instance.
   # In this way, only one instance of the script should run.
   #


   findwindow = Win32API.new('user32','FindWindow', ['p','p'], 'L')
   return true if findwindow.call("STATIC", "i4FileProcessorHiddenWindow") != 0
   createwindow = Win32API.new('user32', 'CreateWindowEx', ['l', 'p',
'p', 'l', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'P'], 'l')
   dwStyle = (WS_DISABLED | WS_MINIMIZED)
   cw = createwindow.call( WS_OVERLAPPED, 'STATIC',
'i4FileProcessorHiddenWindow', dwStyle, 0, 0, 0, 0, 0, 0, 0, 0 )
   show = Win32API.new('user32',  'ShowWindow', ['L', 'L'], 'L')
   show.call(cw, SW_HIDE)


   return false
 end