Add tags

Add tags to the following comment
私が使ってるライブラリそのものですが。私はこのコードを ocean/clipboard.py として保存してるので、

import ocean.clipboard as c
c.get() # クリップボードの中身を取得
c.set("hoge") # クリップボードに設定
c.clear() # クリップボードを空にする

として使います。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from __future__ import with_statement
from contextlib import contextmanager
import ctypes

GMEM_DDESHARE = 0x2000
GMEM_MOVEABLE = 0x0002
CF_TEXT = 1

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

@contextmanager
def _GlobalLock(h):
    p = kernel32.GlobalLock(h)
    if not p:
        raise WindowsError("GlobalLock() failed")
    try:
        yield p
    finally:
        kernel32.GlobalUnlock(h)

@contextmanager
def _Clipboard():
    if not user32.OpenClipboard(None):
        raise WindowsError("OpenClipboard() failed")
    try:
        yield
    finally:
        user32.CloseClipboard()

def set(s):
    s = s.encode("mbcs")
    # memory block
    h = kernel32.GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len(s) + 1)
    if not h:
        raise WindowsError("GlobalAlloc() failed")
    try:
        with _GlobalLock(h) as p:
            p = (ctypes.c_char * (len(s) + 1)).from_address(p)
            for i, c in enumerate(s + "\0"):
                p[i] = c
        # clipboard
        with _Clipboard():
            user32.EmptyClipboard()
            user32.SetClipboardData(CF_TEXT, h)
    except:
        kernel32.GlobalFree(h)
        raise

def get():
    with _Clipboard():
        h = user32.GetClipboardData(CF_TEXT)
        if h:
            with _GlobalLock(h) as p:
                return ctypes.c_char_p(p).value.decode("mbcs")

def clear():
    with _Clipboard():
        user32.EmptyClipboard()

Add tags

The input will be splited to tags with space.

Index

Feed

Other

Link

Pathtraq

loading...