Exemple #1
0
 def clipboard(self,src,fmt):
     import win32clipboard as clip
     clip.OpenClipboard()
     clip.EmptyClipboard()
     try:
         data = open(os.path.join(self.dir,src),'rb').read()
         if fmt == 'BMP':
             # to copy BMP data to the clipboard we need to generate the appropriate BITMAP header
             # let's cheat instead by using PIL to open the PNG, write a temporary BMP and 
             from PIL import Image
             png = Image.open(os.path.join(self.dir,src))
             src += '.bmp'
             # BMP does not really RGBA, so blend with white
             # https://stackoverflow.com/questions/9166400/convert-rgba-png-to-rgb-with-pil
             bmp = Image.new("RGB", png.size, (255, 255, 255))                
             bmp.paste(png, mask=png.split()[3])
             buffer = StringIO.StringIO() # use a StringIO object instead of a temp file
             bmp.save(buffer,format='bmp')
             iformat = clip.CF_DIB
             data = buffer.getvalue()[14:] # bypass the BITMAPFILEHEADER
         elif fmt == 'PNG':
             iformat = clip.RegisterClipboardFormat('PNG')
         elif fmt == 'PDF':
             iformat = clip.RegisterClipboardFormat('Portable Document Format')
         elif fmt == 'EPS':
             iformat = clip.RegisterClipboardFormat('Encapsulated PostScript')
         clip.SetClipboardData(iformat,data)
     except Exception as E:
         clip.CloseClipboard()
         raise   # ensure clipboard closed, then reraise
     clip.CloseClipboard()
     return True
Exemple #2
0
def copy_clipboard(data):
    HTML_ID = win32clipboard.RegisterClipboardFormat("HTML Format")
    CSV_ID = win32clipboard.RegisterClipboardFormat("Csv")

    win32clipboard.OpenClipboard(0)
    win32clipboard.EmptyClipboard()

    win32clipboard.SetClipboardData(HTML_ID, data)
    win32clipboard.SetClipboardData(CSV_ID, b'csv dump')

    win32clipboard.CloseClipboard()
Exemple #3
0
class KeyboardHook:
    pasteCallback = None

    CFSTR_INETURL = win32clipboard.RegisterClipboardFormat(
        "UniformResourceLocator")
    CFSTR_FoobarPlayableLocationFormat = win32clipboard.RegisterClipboardFormat(
        "foobar2000_playable_location_format")

    def __init__(self):
        def keyboard_hook(nCode, wParam, lParam):
            try:
                if not self.pasteCallback:
                    return 0

                if wParam == 0x56 and not self.getBit(lParam, 31):
                    if self.keyDown(win32con.VK_CONTROL) and not self.keyDown(
                            win32con.VK_SHIFT) and not self.keyDown(
                                win32con.VK_MENU):
                        if not self.isClipboardEmpty():
                            invokeCallback(self.pasteCallback)

                # Be a good neighbor and call the next hook.
                #windll.user32.CallNextHookEx(hookId, nCode, wParam, lParam)
                return 0
            except Exception as inst:
                appendLog("Error in keyboard hook: " + str(inst))
                return 0

        hookCallbackPtr = CFUNCTYPE(c_int, c_int, c_int, c_int)(keyboard_hook)
        installHook(win32con.WH_KEYBOARD, hookCallbackPtr)

    def setPasteCallback(self, callback):
        self.pasteCallback = callback

    def isClipboardEmpty(self):
        try:
            win32clipboard.OpenClipboard()

            return (not win32clipboard.IsClipboardFormatAvailable(
                win32con.CF_HDROP)
                    and not win32clipboard.IsClipboardFormatAvailable(
                        self.CFSTR_FoobarPlayableLocationFormat)
                    and not win32clipboard.IsClipboardFormatAvailable(
                        self.CFSTR_INETURL))
        finally:
            win32clipboard.CloseClipboard()

    def getBit(self, byteval, idx):
        return (byteval & (1 << idx)) != 0

    def keyDown(self, key):
        return self.getBit(win32api.GetAsyncKeyState(key), 15)
 def set_clipboard(data):
     win32clipboard.OpenClipboard()
     win32clipboard.EmptyClipboard()
     encoded_data = data.encode('utf-8')
     format = win32clipboard.RegisterClipboardFormat('XML SpreadSheet')
     win32clipboard.SetClipboardData(format, encoded_data)
     win32clipboard.CloseClipboard()
Exemple #5
0
    def GetCfHtml(self):
        """
        Return the FORMATID of the HTML format
        """
        if self.CF_HTML is None:
            self.CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")

        return self.CF_HTML
def copyfig(fig=None, *args, **kwargs):
    """
    Parameters
    ----------
    fig : matplotlib figure, optional
        if None, get the figure that has UI focus
    *args : arguments that are passed to savefig
    
    **kwargs : keywords arguments that are passed to savefig

    Raises
    ------
    ValueError
        If the desired format is not supported.
        
    AttributeError
        If no figure is found

    """
    #By digging into windows API
    format_dict = {
        "png": "PNG",
        "svg": "image/svg+xml",
        "jpg": "JFIF",
        "jpeg": "JFIF"
    }

    #if no format is passed to savefig get the default one
    format = kwargs.get('format', plt.rcParams["savefig.format"])
    format = format.lower()

    if not format in format_dict:
        raise ValueError(f"Format {format} is not supported "\
                         f"(supported formats: {', '.join(list(format_dict.keys()))})")

    if fig is None:
        # find the figure window that has UI focus right now (not necessarily the same as plt.gcf())
        fig_window_text = GetWindowText(GetForegroundWindow())
        for i in plt.get_fignums():
            if plt.figure(i).canvas.get_window_title() == fig_window_text:
                fig = plt.figure(i)
                break

    if fig is None:
        raise AttributeError("No figure found !")

    formatID = win32clipboard.RegisterClipboardFormat(format_dict[format])
    with BytesIO() as buf:
        fig.savefig(buf, *args, **kwargs)
        data = buf.getvalue()

    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(formatID, data)
    win32clipboard.CloseClipboard()
Exemple #7
0
def get_paste_buffer():
    cl.OpenClipboard(0)
    cfHtml = cl.RegisterClipboardFormat("HTML Format")
    try:
        result = cl.GetClipboardData(cfHtml)
    except TypeError:
        result = "unknown"  #non-text
    cl.CloseClipboard()
    if result != "unknown":
        result = result.decode("utf-8", errors="ignore")
    return result
Exemple #8
0
    def register_clipboard_formats(self):
        """
        Here we extract all of the formats from the qmimedata object and
        register them.  This will give us an ID for each type.
        This will return a dictionary with the ID's and descriptions for
        each mime type.
        """
        mime_formats = mimeData.formats()
        format_dictionary = dict()
        for format in mime_formats:
            id = win32clipboard.RegisterClipboardFormat(str(format))
            format_dictionary[id] = format

        return format_dictionary
Exemple #9
0
def copy():
    if os.name == 'nt':
        import win32clipboard
        win32clipboard.OpenClipboard(0)
        win32clipboard.EmptyClipboard()
        win32clipboard.CloseClipboard()
        time.sleep(.1)

        __ctrl_c()
        time.sleep(.1)

        win32clipboard.OpenClipboard(0)

        if not win32clipboard.IsClipboardFormatAvailable(
                win32clipboard.CF_TEXT):
            text = ""
        else:
            text = win32clipboard.GetClipboardData()

        if not win32clipboard.IsClipboardFormatAvailable(
                win32clipboard.RegisterClipboardFormat("HTML Format")):
            html = ""
        else:
            html = win32clipboard.GetClipboardData(
                win32clipboard.RegisterClipboardFormat("HTML Format")).decode(
                    'utf-8')

        if not win32clipboard.IsClipboardFormatAvailable(
                win32clipboard.RegisterClipboardFormat('Rich Text Format')):
            rtf = ""
        else:
            rtf = win32clipboard.GetClipboardData(
                win32clipboard.RegisterClipboardFormat('Rich Text Format'))

        win32clipboard.CloseClipboard()

        return text, html, rtf
Exemple #10
0
    def copy_to_clipboard(self):
        CF_RTF = w32c.RegisterClipboardFormat("Rich Text Format")

        string_copy = "{\\rtf1\\ansi\\deff0 {\\pard "

        for keys in self._npc_profile:
            string_copy = string_copy + '\\b {}: \\b0 {} \line'.format(
                keys, self._npc_profile[keys])

        string_copy = string_copy + '\\par}}'

        rtf = bytearray(string_copy, 'utf8')
        w32c.OpenClipboard(0)
        w32c.EmptyClipboard()
        w32c.SetClipboardData(CF_RTF, rtf)
        w32c.CloseClipboard()
        return "Copied to clipboard"
 def __init__(self):
     #前缀模板 长度97
     self.prefix = "Version:1.0\r\nStartHTML:00000097\r\nEndHTML:%8d\r\nStartFragment:00000191\r\nEndFragment:%8d\r\n<!DOCTYPE html><HTML><HEAD><TITLE>HTML To Clipboard!</TITLE></HEAD><BODY><!--StartFragment -->"
     #后缀模板 长度33 EndHTML = EndFragment + 33
     self.suffix = "<!--EndFragment --></BODY></HTML>"
     #html代码
     self.fragment = ''
     #self.selection = None
     #self.source = None
     #self.htmlClipboardVersion = None
     '''
     下面为注册"HTML Format"格式的过程。注册函数返回一个整数数字,该数字为剪贴板将内容识别为html的关键参数。在本人的运行环境中该数字固定为49388
     '''
     try:
         self.CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
         report("self.__init__:注册HTML格式成功!CF_HTML值为", self.CF_HTML)
     except:
         report("self.__init__:注册HTML格式失败!")
Exemple #12
0
def get_citations():
    """
    Returns the contents of the specified CITATIONS format when opening following URL: https://localhost:5000/source.py

    :return: Current clipboard citations in JSON format
    """
    try:
        # Try to get the clipboard's text. If no text is available, set "No Text available" as text
        clp.OpenClipboard(None)
        try:
            text = unicode(clp.GetClipboardData(clp.CF_TEXT), errors='replace')
        except:
            text = "No Text available"

        # Register citation format, so we can check if this format is available
        citation_format = clp.RegisterClipboardFormat("CITATIONS")
        # Checks if citations are available, then returns them as JSON
        if clp.IsClipboardFormatAvailable(citation_format):
            data = clp.GetClipboardData(citation_format)
            clp.CloseClipboard()
            return data

        else:
            # If format is unavailable, set placeholders as data and return JSON object
            clp.CloseClipboard()
            data = {}
            data['APA'] = "no citations in clipboard"
            data['AMA'] = "no citations in clipboard"
            data['content'] = text
            json_data = json.dumps(data)
            return json_data
    except:
        # If anything above fails, close the clipboard und return placeholders as JSON object
        try:
            clp.CloseClipboard()
        except:
            print "clipboard already closed"

        data = {}
        data['APA'] = "no citations in clipboard"
        data['AMA'] = "no citations in clipboard"
        data['content'] = "no text in clipboard"
        json_data = json.dumps(data)
        return json_data
Exemple #13
0
def registerCustomClipboardFormat():
    '''Registers a custom clipbord format to detect internal clipboard
    changes.

    We need to be able to detec whether a clipboard change is due to our 
    own functions or an outside source, in order to make sure that pasting
    does not add entries to the clipboard history.

    Returns:
        The id of the custom format
        int

    Raises:
        RuntimeError: Raises an error if for any reason we can't register
        a clipboard format.
    '''
    customFormatID = win32clipboard.RegisterClipboardFormat("vsClipboardPaste")
    if customFormatID == 0:
        raise RuntimeError("Could not register custom clipboard format")
    return customFormatID
Exemple #14
0
async def Check_clipboard_links(drive):  #Only works for windows
    # Ressource : https://stackoverflow.com/questions/55698762/how-to-copy-html-code-to-clipboard-using-python
    if os.name == 'nt':
        import win32clipboard
    else:
        raise OSError("os isn't windows !")
    CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
    cacheClipboard = ""
    while 1:
        await asyncio.sleep(1)
        win32clipboard.OpenClipboard(0)
        try:
            src = win32clipboard.GetClipboardData(CF_HTML).decode("UTF-8")
        except TypeError:  #if not html
            try:
                src = win32clipboard.GetClipboardData(
                    win32clipboard.CF_TEXT).decode("UTF-8")
            except TypeError:
                src = ""
        win32clipboard.CloseClipboard()
        if (src != cacheClipboard
            ):  #avoid downloading infinite loop if still in clipboard
            cacheClipboard = src
            Copy_dwnld_from_links(src, drive)
Exemple #15
0
def past(text, html=None, rtf=None):
    if os.name == 'nt':
        import win32clipboard
        win32clipboard.OpenClipboard(0)
        win32clipboard.EmptyClipboard()

        if text:
            win32clipboard.SetClipboardText(text,
                                            win32clipboard.CF_UNICODETEXT)
        if html:
            win32clipboard.SetClipboardData(
                win32clipboard.RegisterClipboardFormat("HTML Format"),
                bytearray(html, 'utf-8'))

        win32clipboard.CloseClipboard()

        time.sleep(.1)

        __ctrl_v()

        time.sleep(.1)
        win32clipboard.OpenClipboard(0)
        win32clipboard.EmptyClipboard()
        win32clipboard.CloseClipboard()
Exemple #16
0
import win32clipboard
import sys

CF_RTF = win32clipboard.RegisterClipboardFormat("Rich Text Format")

rawrtf = ""
for line in sys.stdin:
    if 'q' == line.rstrip():
        break
    rawrtf += line

rtf = bytearray(rawrtf, 'utf8')

win32clipboard.OpenClipboard(0)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(CF_RTF, rtf)
win32clipboard.CloseClipboard()
# pandoc --standalone --from=gfm --to=rtf --output=- $1 | /mnt/c/Python38/python.exe c:\\runbox\\rtfclip.py
Exemple #17
0
def main():
    parser = argparse.ArgumentParser(allow_abbrev=False)

    input = parser.add_mutually_exclusive_group(required=True)
    output = parser.add_mutually_exclusive_group(required=True)

    input.add_argument("--File", metavar="File", help="File to format")
    output.add_argument("--OutputFile",
                        metavar="OutputFile",
                        help="HTML file to output")

    parser.add_argument(
        "--lexer",
        help="Lexer to be used(see lexer.txt for options, default python)",
        default="python")
    parser.add_argument(
        "--style",
        help="Color style to use(see style.txt for options, default vs)",
        default="vs")
    parser.add_argument("--linenos",
                        help="Include line number",
                        action="store_true")
    if FOUND_WIN32_CLIPBOARD:
        output.add_argument("--copytoclipboard",
                            help="Copy to clipboard(windows, pywin32 only)",
                            action="store_true")
        input.add_argument("--copyfromclipboard",
                           help="Copy from clipboard(windows, pywin32 only)",
                           action="store_true")

    arg = parser.parse_args()

    if arg.copyfromclipboard and FOUND_WIN32_CLIPBOARD:
        win32clipboard.OpenClipboard()
        text = win32clipboard.GetClipboardData(
            win32clipboard.CF_UNICODETEXT).encode()
        win32clipboard.CloseClipboard()
    else:
        file_str = arg.File
        file_obj = open(file_str, "rb")
        text = file_obj.read()
        file_obj.close()

    data = {
        "code": text.decode(),
        "lexer": arg.lexer,
        "style": arg.style,
        "divstyles": ""
    }
    if arg.linenos:
        data["linenos"] = "true"

    r = requests.post("http://hilite.me/api", data=data)
    text = r.content

    if arg.copytoclipboard and FOUND_WIN32_CLIPBOARD:
        clipboard_data_format = r"Version:0.9\r\n" \
                                 "StartHTML:{:09d}\r\n" \
                                 "EndHTML:{:09d}\r\n" \
                                 "StartFragment:{:09d}\r\n" \
                                 "EndFragment:{:09d}\r\n" \
                                 "<!doctype>\r\n" \
                                 "<html>\r\n" \
                                 "<body>\r\n" \
                                 "<!--StartFragment -->\r\n" \
                                 "{}\r\n" \
                                 "<!--EndFragment -->\r\n" \
                                 "</body>\r\n" \
                                 "</html>\r\n"

        prefix = r"Version:0.9\r\n" \
                  "StartHTML:{:09d}\r\n" \
                  "EndHTML:{:09d}\r\n" \
                  "StartFragment:{:09d}\r\n" \
                  "EndFragment:{:09d}\r\n"

        text = text.decode()

        data_for_prefix = prefix.format(0, 0, 0, 0)
        len_prefix = len(data_for_prefix)

        data_for_prefix = clipboard_data_format.format(0, 0, 0, 0, text)
        data_len = len(text)

        start_data = data_for_prefix.index(text)
        end_data = start_data + data_len
        actual_formatted_data = clipboard_data_format.format(
            len_prefix, len(data_for_prefix), start_data, end_data, text)

        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardData(
            win32clipboard.RegisterClipboardFormat("HTML Format"),
            actual_formatted_data.encode("UTF-8"))
        win32clipboard.CloseClipboard()
    else:
        file_obj = open(arg.OutputFile, "wb")
        file_obj.write(text)
        file_obj.close()
Exemple #18
0
 def register_format(self, format_name):
     return win32clipboard.RegisterClipboardFormat(format_name)
Exemple #19
0
from pygments import highlight
from pygments.lexers.c_cpp import CppLexer
from pygments.formatters import RtfFormatter
from pygments.style import Style
from pygments.styles import STYLE_MAP
import sys
import win32clipboard as clippy

# Stylizer settings
styles = list(STYLE_MAP.keys()) # Available styles
style = styles[6]
font = "Monaco"
fontsize = 24


# Get input and style it
input = str(sys.argv[1])

output = highlight(input, CppLexer(), RtfFormatter(style=style, fontface=font, fontsize=fontsize))


# Copy to clipboard
CF_RTF = clippy.RegisterClipboardFormat("Rich Text Format")

output = bytearray(output, "utf8")

clippy.OpenClipboard(0)
clippy.EmptyClipboard()
clippy.SetClipboardData(CF_RTF, output)
clippy.CloseClipboard()
Exemple #20
0
 def _getCFFormatCode(self, cfFormatName):
     try:
         return win32clipboard.RegisterClipboardFormat(cfFormatName)
     except:
         return -1
Exemple #21
0
class ClipboardState:
    """
    A class that encapsulates a state of the clipboard.  Upon
    intialization it stores the current state of the clipboard.
    """

    # List of clipboard formats that we save.  (We whitelist, rather
    # than blacklist, formats.)  This is far from all the clipboard
    # formats that there are, but Unicode, RTF, and Device Independent
    # Bitmap cover most of the bases.  It should be noted that a
    # number of similar formats, such as CF_TEXT and CF_BITMAP, are
    # automatically synthesized by Windows from some of the clipboard
    # formats we save, which means that we don't need to explicitly
    # save them ourselves.

    # LONGTERM TODO: Add more formats here when it is determined that
    # we have the need and the ability to save them.
    _SAVED_FORMATS = [
        win32con.CF_UNICODETEXT, win32con.CF_DIB,
        win32clipboard.RegisterClipboardFormat("Rich Text Format")
    ]

    # LONGTERM TODO: If a user is running, say, Photoshop, and they
    # copy some massive chunk of graphics, Photoshop is probably doing
    # delayed clipboard rendering.  If this class is then called on to
    # save the clipboard state, it will force Photoshop to actually
    # render the massive chunk of graphics, which takes lots of time
    # and memory.  So this may become a performance issue at some
    # point.  OTOH, there may not be any other alternative; more
    # research needs to be done.

    # LONGTERM TODO: When saving the clipboard state, we're not
    # currently preserving the order in which the clipboard formats
    # were put on the clipboard.  This may be something we want to do
    # in the future, since some programs may rely on it to figure out
    # what the most 'useful' or 'high-priority' clipboard format is.

    @ContextUtils.clipboardDependent
    def __init__(self):
        """
        Reads current state of clipboard, creates a ClipboardState
        object duplicating that state.
        """

        logging.debug("Attempting to save clipboard data in \
                   ClipboardState object")

        self.__formatData = {}

        for format in self._SAVED_FORMATS:
            if win32clipboard.IsClipboardFormatAvailable(format):
                try:
                    dataHandle = win32clipboard.GetClipboardDataHandle(format)
                except win32clipboard.error as e:
                    # This is a fix for ticket #414.
                    if e.args[0] == 0:
                        logging.info("GetClipboardData error suppressed.")
                        continue
                    else:
                        raise

                rawData = win32clipboard.GetGlobalMemory(dataHandle)
                self.__formatData[format] = rawData

    @ContextUtils.clipboardDependent
    def restore(self):
        """
        Puts the data contained in this object back into the
        clipboard.
        """

        logging.debug("Attempting to restore clipboard data from"
                      " ClipboardState object")

        win32clipboard.EmptyClipboard()

        for format in list(self.__formatData.keys()):
            rawData = self.__formatData[format]
            win32clipboard.SetClipboardData(format, rawData)

        ContextUtils.setClipboardDataViewerIgnore()

    def __getClipboardFormatList(self):
        """
        Returns a list of strings corresponding to the formats
        currently contained in the clipboard, useful for debugging
        purposes.

        Precondition: the clipboard is open.
        Postcondition: the clipboard is open.
        """

        format = 0
        done = False
        formatNames = []
        while not done:
            format = win32clipboard.EnumClipboardFormats(format)
            if format == 0:
                done = True
            else:
                formatName = ContextUtils.interpretFormatCode(format)
                if not formatName:
                    formatName = "Unknown format %d" % format
                formatNames.append(formatName)
        return formatNames
Exemple #22
0
import win32api
import win32clipboard as wc
import Image
from PIL import ImageGrab
# Thanks to http://stackoverflow.com/a/7045677/151453

# sys.path.append( os.path.join(os.path.dirname(__file__),'../_pyshare'));
import selfclean_tempfile

DEFAULT_JPG_QUALITY = 60
NOT_PNG = 0

CB_TEXT = 'text'
CB_HTML = 'html'

CF_HTML = wc.RegisterClipboardFormat("HTML Format")

CF_FileNameW = wc.RegisterClipboardFormat("FileNameW")
# Ways to get "FileNameW" clipboard format:
# 1. Copy a file in Windows Explorer.
# 2. From within a Evernote v5 clip, right click an image, select Copy from context menu.

sys_codepage = locale.getpreferredencoding(True)
g_imghint = ""  # example: "PNG(32-bit)"


def MakeUnicodePath(path):
    if type(path) != unicode:
        path = unicode(path, sys_codepage)
    return path
Exemple #23
0
# A demo for the IDsObjectPicker interface.
import win32clipboard
import pythoncom
from win32com.adsi import adsi
from win32com.adsi.adsicon import *

cf_objectpicker = win32clipboard.RegisterClipboardFormat(
    CFSTR_DSOP_DS_SELECTION_LIST)


def main():
    hwnd = 0

    # Create an instance of the object picker.
    picker = pythoncom.CoCreateInstance(adsi.CLSID_DsObjectPicker, None,
                                        pythoncom.CLSCTX_INPROC_SERVER,
                                        adsi.IID_IDsObjectPicker)

    # Create our scope init info.
    siis = adsi.DSOP_SCOPE_INIT_INFOs(1)
    sii = siis[0]

    # Combine multiple scope types in a single array entry.

    sii.type = DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN | \
        DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN

    # Set uplevel and downlevel filters to include only computer objects.
    # Uplevel filters apply to both mixed and native modes.
    # Notice that the uplevel and downlevel flags are different.
Exemple #24
0
# be unopenable, but with increased wait times for users. However,
# it should also be remembered that if some application has
# ownership of the clipboard, they should release it very soon,
# and if the system is very busy, this may understandably take
# a lot of time.
CLIPBOARD_OPEN_WAIT_AMOUNT = 1000

# The following three constants are obtained programatically.
# Since this code is executed the first time that ContextUtils is
# imported, and it is imported in __init__.py, these constants
# should always be available for other modules to import.

# Clipboard format code for ThornSoft's CF_CLIPBOARD_VIEWER_IGNORE
# format.  For more information, see
# http://www.thornsoft.com/developer_ignore.htm.
CF_CLIPBOARD_VIEWER_IGNORE = win32clipboard.RegisterClipboardFormat(
    "Clipboard Viewer Ignore")

# Clipboard formats for HTML and RTF are, annoyingly, not constant
# numbers; Windows reserves the right to vary them between runs;
# but we can fetch their current values as follows:
CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
CF_RTF = win32clipboard.RegisterClipboardFormat("Rich Text Format")

# Keyboard event types.  According to MSDN documentation:
# "KEYEVENTF_KEYUP
#    If specified, the key is being released. If not specified, the
#    key is being depressed."
KEYEVENTF_KEYDOWN = 0
KEYEVENTF_KEYUP = win32con.KEYEVENTF_KEYUP

# ----------------------------------------------------------------------------
Exemple #25
0
import time, win32clipboard
from datetime import datetime

message = raw_input("your message : ")
author = raw_input("author : ")
date = raw_input("date : ")

date_epoch = 0

if date == "":
	now = datetime.now()
	date_epoch = time.mktime(now.timetuple())
else :
	date_epoch = time.mktime(datetime.strptime(date, '%d%m%Y %H%M').timetuple())

quote = '<quote author="%s" timestamp="%d">%s</quote>' % (author, date_epoch, message)

win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(1,quote)
win32clipboard.SetClipboardData(7,quote)
win32clipboard.SetClipboardData(win32clipboard.RegisterClipboardFormat("skypeMessageFragment"),quote)
win32clipboard.CloseClipboard()
Exemple #26
0
clips = []
currentIndex = []

# Used for getting application name and path
window_management_instrumentation = wmi.WMI()

# Copying in PDFs fires multiple events, so the contents are stored here and then checked if they have changed
last_clipboard_content_for_pdf = []

# Wiki Base URLs for retrieving metadata
wikipedia_base_url_german = "https://de.wikipedia.org"
wikipedia_base_url = "https://en.wikipedia.org"
wikimedia_base_url = 'https://commons.wikimedia.org'

# Register custom clipboard formats
citation_format = clp.RegisterClipboardFormat("CITATIONS")
src_format = clp.RegisterClipboardFormat("SOURCE")
metadata_format = clp.RegisterClipboardFormat("METADATA")

# Array to check window ID when copying out of PDF
pdf_window_id = []


def main():
    """
    Main method, sets up clipboard connection and PyQt Loop
    """

    # Connects the clipboard changed event to clipboardChanged function
    clipboard.dataChanged.connect(clipboard_changed)
Exemple #27
0
#     otherwise the \n will always translate into \r\n
# --2011.01.19 AM 09:49 Modified by xialulee--
#   add -N, --null option, indicate to discard the bytes behind the null character
# --2011.01.19 AM 10:47 Modified by xialulee--
#   add -e, --encode option, indicate to encode the unicode string comes from clipboard
# --2015.03.12 PM 08:55 Modified by xialulee--
#   add new function image2clipb
# --2015.03.13 PM 04:05 Modified by xialulee--
#   add --html option. Now support writing HTML string to clipboard.
#
# --ActivePython2.6.6.15--
# --xialulee--

ERROR_NOERROR, ERROR_PARAM, ERROR_CLIPB = range(3)
NEWLINE = re.compile(r'(?<!\r)\n')
CF_HTML = win32clipboard.RegisterClipboardFormat('HTML Format')

def clipb2stdout(mode, code, null):
    exitcode = ERROR_NOERROR
    win32clipboard.OpenClipboard(0)
    try:
        s = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    except TypeError:
        sys.stderr.write('Clipb-Error: Data in clipboard is not TEXT FORMAT!\n')
        exitcode = ERROR_CLIPB
    else:
        if code:
            s = s.encode(code, 'ignore')
        if null:
            s = s[:s.index('\x00')]
        if mode == 't':