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



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

def clear
  if 0 != User32.open( 0 )
    User32.empty( )
    User32.close( )
  end
  paste
end

#copy(data_to_copy) ⇒ Object



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

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

#paste(_ = nil) ⇒ Object



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

def paste(_ = nil)
  data = +""
  if 0 != User32.open( 0 )
    hclip = User32.get( CF_UNICODETEXT )
    if hclip && 0 != hclip
      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.get_bytes( 0, size - 2 )
      data.force_encoding("UTF-16LE")
      Kernel32.unlock( hclip )
    end
    User32.close( )
  end
  data
end