Module: Clipboard::Windows

Extended by:
Windows
Included in:
Windows
Defined in:
lib/clipboard/windows.rb

Defined Under Namespace

Modules: Kernel32, User32

Constant Summary collapse

CF_TEXT =
1
CF_UNICODETEXT =
13
GMEM_MOVEABLE =
2

Instance Method Summary collapse

Instance Method Details

#clearObject



60
61
62
63
64
65
# File 'lib/clipboard/windows.rb', line 60

def clear
  User32.empty if User32.open(nil)
  paste
ensure
  User32.close
end

#copy(data_to_copy) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/clipboard/windows.rb', line 67

def copy(data_to_copy)
  if User32.open(nil)
    User32.empty
    data = data_to_copy.encode(Encoding::UTF_16LE) # TODO: catch bad encodings
    data << 0
    handler = Kernel32.alloc( GMEM_MOVEABLE, data.bytesize )
    pointer_to_data = Kernel32.lock( handler )
    begin
      pointer_to_data.write_string( data )
    ensure
      Kernel32.unlock( handler )
    end
    User32.set( CF_UNICODETEXT, handler )
    data.chop
  else # don't touch anything
    Utils.popen "clip", data_to_copy # depends on clip (available by default since Vista)
    paste
  end
ensure
  User32.close
end

#paste(_ = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/clipboard/windows.rb', line 44

def paste(_ = nil)
  return String.new unless User32.open(nil)

  hclip = User32.get( CF_UNICODETEXT )
  return String.new if hclip.null?

  pointer_to_data = Kernel32.lock( hclip )
  # Windows Unicode is ended by two null bytes, so get the whole string
  size = Kernel32.size( hclip )
  data = pointer_to_data.read_string( size - 2 )
  data.force_encoding(Encoding::UTF_16LE)
ensure
  Kernel32.unlock(hclip) if hclip && !hclip.null?
  User32.close
end