Clipboard.cpp 1.6 KB
Newer Older
Gargaj's avatar
Gargaj committed
1
#include <Windows.h>
Gargaj's avatar
Gargaj committed
2

Gargaj's avatar
Gargaj committed
3
namespace Clipboard
Gargaj's avatar
Gargaj committed
4
{
Gargaj's avatar
Gargaj committed
5
6
7
  void Copy( const char * data, int len )
  {
    HWND hWnd = GetForegroundWindow();
8
    if ( !::OpenClipboard( hWnd ) )
Gargaj's avatar
Gargaj committed
9
      return;
Gargaj's avatar
Gargaj committed
10

11
12
13
14
15
    HGLOBAL hData = GlobalAlloc( GMEM_MOVEABLE, ( len + 1 ) * sizeof( char ) );
    if ( !hData ) {
      CloseClipboard();
      return;
    }
Gargaj's avatar
Gargaj committed
16

17
18
19
20
21
22
    WCHAR * pMem = (WCHAR*) GlobalLock( hData );
    if ( !pMem ) {
      GlobalFree( hData );
      CloseClipboard();
      return;
    }
Gargaj's avatar
Gargaj committed
23

24
25
    ZeroMemory( pMem, ( len + 1 ) * sizeof( char ) );
    CopyMemory( pMem, data, ( len + 1 ) * sizeof( char ) );
Gargaj's avatar
Gargaj committed
26

27
28
29
30
31
    GlobalUnlock( hData );

    EmptyClipboard();

    SetClipboardData( CF_TEXT, hData );
Gargaj's avatar
Gargaj committed
32

Gargaj's avatar
Gargaj committed
33
34
    CloseClipboard();
  }
Gargaj's avatar
Gargaj committed
35

Gargaj's avatar
Gargaj committed
36
37
38
  int GetContentsLength()
  {
    HWND hWnd = GetForegroundWindow();
39
    if ( !::OpenClipboard( hWnd ) )
Gargaj's avatar
Gargaj committed
40
      return 0;
Gargaj's avatar
Gargaj committed
41

42
    HANDLE hData = GetClipboardData( CF_TEXT );
43
44
45
46
47
    if ( !hData ) {
      CloseClipboard();
      return 0;
    }

48
    const char * buffer = (const char*) GlobalLock( hData );
49
50
51
52
53
    if ( !buffer ) {
      CloseClipboard();
      return 0;
    }

54
    int n = strlen( buffer );
Gargaj's avatar
Gargaj committed
55

56
57
    GlobalUnlock( hData );

Gargaj's avatar
Gargaj committed
58
    CloseClipboard();
Gargaj's avatar
Gargaj committed
59

Gargaj's avatar
Gargaj committed
60
61
    return n;
  }
Gargaj's avatar
Gargaj committed
62

Gargaj's avatar
Gargaj committed
63
64
65
  void GetContents( char * data, int len )
  {
    HWND hWnd = GetForegroundWindow();
66
    if ( !::OpenClipboard( hWnd ) )
Gargaj's avatar
Gargaj committed
67
      return;
Gargaj's avatar
Gargaj committed
68

69
    HANDLE hData = GetClipboardData( CF_TEXT );
70
71
72
73
74
    if ( !hData ) {
      CloseClipboard();
      return;
    }

75
    const char * buffer = (const char*) GlobalLock( hData );
76
77
78
79
80
    if ( !buffer ) {
      CloseClipboard();
      return;
    }

Gargaj's avatar
Gargaj committed
81
    strncpy( data, buffer, len );
Gargaj's avatar
Gargaj committed
82

83
84
    GlobalUnlock( hData );

Gargaj's avatar
Gargaj committed
85
86
    CloseClipboard();
  }
Gargaj's avatar
Gargaj committed
87
88

}