def main(window): try: import win32clipboard except: window.dialogCritical("Cannot import win32clipboard", "pywin32 needs to be installed to use this\n(pip install pypiwin32)") return False try: from PIL import ImageGrab except: window.dialogCritical("Cannot import PIL.ImageGrab", "PIL needs to be installed to use this\n(pip install Pillow)") return False from PyQt5.QtWidgets import QFileDialog if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT): win32clipboard.OpenClipboard() clipboard = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() fileName, _ = QFileDialog.getSaveFileName(window, "QFileDialog.getSaveFileName()", None, "Text Files (*.txt)") if fileName == '': return True f = open(fileName, 'w') f.write(clipboard) f.close() elif win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_BITMAP): im = ImageGrab.grabclipboard() fileName, _ = QFileDialog.getSaveFileName(window, "QFileDialog.getSaveFileName()", None, "Text Files (*.bmp)") if fileName == '': return True im.save(fileName, 'BMP') return True
def get_data(cls, dir_img=None): data_type = data_content = None clip.OpenClipboard(0) # 打开剪贴板 if clip.IsClipboardFormatAvailable(clip.CF_HDROP): # 如果是文件格式 data_content = [ file for file in clip.GetClipboardData(clip.CF_HDROP) ] clip.CloseClipboard() data_type = cls.DATA_TYPE_FILE elif clip.IsClipboardFormatAvailable(clip.CF_DIB): # 如果是图片格式 if dir_img: # 如果设置了图片目录,则将剪贴板的图片内容保存到该目录 data = clip.GetClipboardData(clip.CF_DIB) clip.CloseClipboard() data_content = cls.save_img(data=data, dir_img=dir_img) # 保存图片 else: clip.CloseClipboard() data_type = cls.DATA_TYPE_IMG elif clip.IsClipboardFormatAvailable(clip.CF_UNICODETEXT): # 如果是文本格式 data_content = clip.GetClipboardData( clip.CF_UNICODETEXT).split("\r\n") clip.CloseClipboard() data_type = cls.DATA_TYPE_TEXT else: clip.CloseClipboard() data_type = cls.DATA_TYPE_OTHR return (data_type, data_content)
def _getClipboardText(self): """ Attempts to get text from clipboard, create a textDict wrapping it, and return the dictionary; takes care of opening and closing the clipboard. If nothing is available, returns an empty dict. """ # We attempt to get two pieces of information from the clipboard: # the formatted text and the plain text. # Try to get plaintext from unicode text in clipboard; this # is likely to be a better version of the unformatted text than # what we could produce by stripping out format tags, and it's # also easier to use. if win32clipboard.IsClipboardFormatAvailable(CF_UNICODETEXT): try: plainText = win32clipboard.GetClipboardData(CF_UNICODETEXT) except win32clipboard.error as e: # This is a fix for ticket #415. if e.args[0] == 0: logging.info("GetClipboardData() error suppressed.") return {} else: raise assert isinstance( plainText, str ), \ "GetClipboardData returned not-a-unicode object!!" else: # If UNICODETEXT is not available, then all other # plain-text formats are unavailable; however, # we can fall back on getting the plaintext by stripping # formatting info out of the formatted text. plainText = None # Try to get HTML from clipboard: if win32clipboard.IsClipboardFormatAvailable(CF_HTML): logging.debug("HTML is available, getting it.") formatText = win32clipboard.GetClipboardData(CF_HTML) else: formatText = None # TODO if plainText is none and formatText is not none, then # try to create plainText from formatText by stripping the HTML -- # see how this is done in EnsoTextObject. newTextDict = {} if plainText != None: newTextDict["text"] = plainText if formatText != None: newTextDict["html"] = formatText return newTextDict
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 SwapClipboards(self): if (win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_UNICODETEXT)): win32clipboard.OpenClipboard() curr_clip = win32clipboard.GetClipboardData( win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() pl = self.content self.content = curr_clip if (type(pl) == str): win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, pl) win32clipboard.CloseClipboard() elif (type(pl) == bytes): win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, pl) win32clipboard.CloseClipboard() else: otpt = BytesIO() pl.convert('RGB').save(otpt, 'BMP') win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, otpt.getvalue()[14:]) win32clipboard.CloseClipboard() elif (win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_DIB)): win32clipboard.OpenClipboard() curr_clip = win32clipboard.GetClipboardData(win32clipboard.CF_DIB) win32clipboard.CloseClipboard() plc = self.content self.content = curr_clip if (type(plc) == str): win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, plc) win32clipboard.CloseClipboard() elif (type(plc) == bytes): win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, plc) win32clipboard.CloseClipboard() else: otpt = BytesIO() plc.convert('RGB').save(otpt, 'BMP') win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, otpt.getvalue()[14:]) win32clipboard.CloseClipboard()
def getClipboardImage(): BI_BITFIELDS = 3 win32clipboard.OpenClipboard( ) # https://msdn.microsoft.com/zh-cn/library/windows/desktop/ff468802(v=vs.85).aspx try: if win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_DIB ): # https://msdn.microsoft.com/en-us/library/windows/desktop/ms649013(v=vs.85).aspx data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB) else: print('cliboard does not contain an image in DIB format.') sys.exit(1) finally: win32clipboard.CloseClipboard() BitMapInfoHeaderHandle = BITMAPINFOHEADER() memmove(pointer(BitMapInfoHeaderHandle), data, SIZEOF_BITMAPINFOHEADER) if BitMapInfoHeaderHandle.biCompression != BI_BITFIELDS: print('insupported compression type {}'.format( BitMapInfoHeaderHandle.biCompression)) sys.exit(1) BitMapFileHeaderHandle = BITMAPFILEHEADER() memset(pointer(BitMapFileHeaderHandle), 0, SIZEOF_BITMAPFILEHEADER) BitMapFileHeaderHandle.bfType = ord('B') | (ord('M') << 8) BitMapFileHeaderHandle.bfSize = SIZEOF_BITMAPFILEHEADER + len(data) SIZEOF_COLORTABLE = 0 BitMapFileHeaderHandle.bfOffBits = SIZEOF_BITMAPFILEHEADER + SIZEOF_BITMAPINFOHEADER + SIZEOF_COLORTABLE with open(TEMP_FILE_NAME, 'ab') as bmp_file: bmp_file.write(BitMapFileHeaderHandle) bmp_file.write(data) #保存为系统统一的png格式,使得后续可以识别 im = Image.open(TEMP_FILE_NAME) im.save(TEMP_FILE_NAME) print('file created from clipboard image') #完成图像创建
def main(window): try: import win32clipboard except: window.dialogCritical( "Cannot import win32clipboard", "pywin32 needs to be installed to use this\n(pip install pypiwin32)" ) return False pyuic_path = "C:/Python35/Lib/site-packages/PyQt5/pyuic5.bat" win32clipboard.OpenClipboard() if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_HDROP): current_clipboard = list( win32clipboard.GetClipboardData(win32clipboard.CF_HDROP)) if len(current_clipboard) == 1: if os.path.basename(current_clipboard[0]).endswith(".ui"): file_name = os.path.basename(current_clipboard[0]) folder = os.path.dirname(current_clipboard[0]) os.system(pyuic_path + " " + current_clipboard[0] + " -x -o " + current_clipboard[0][:-2] + 'py') win32clipboard.CloseClipboard() return True
def is_clipboard_hdrop(): win32clipboard.OpenClipboard() is_it_hdrop = False if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_HDROP): is_it_hdrop = True win32clipboard.CloseClipboard() return is_it_hdrop
def __getHdropFiles( self ): """ Private method for fetching the clipboard format CF_HDROP, which represents file targets. """ formatAvailable = win32clipboard.IsClipboardFormatAvailable( win32con.CF_HDROP ) if formatAvailable: try: value = win32clipboard.GetClipboardData( win32con.CF_HDROP ) except pywintypes.error as e: logging.warn( "Error getting CF_HDROP from clipboard: %s" \ % ( str(e) ) ) value = None else: logging.info( "Clipboard type CF_HDROP not in clipboard." ) value = None # LONGTERM TODO: See whether there are other clipboard # formats that could give us the information we need # when CF_HDROP is not available. return value
def _getClipboardText( self ): """ Attempts to get text from clipboard, create a textDict wrapping it, and return the dictionary; takes care of opening and closing the clipboard. If nothing is available, returns an empty dict. """ # We attempt to get two pieces of information from the clipboard: # the formatted text and the plain text. # Try to get plaintext from unicode text in clipboard; this # is likely to be a better version of the unformatted text than # what we could produce by stripping out format tags, and it's # also easier to use. if win32clipboard.IsClipboardFormatAvailable( CF_UNICODETEXT ): try: plainText = win32clipboard.GetClipboardData( CF_UNICODETEXT ) except win32clipboard.error, e: # This is a fix for ticket #415. if e.args[0] == 0: logging.info( "GetClipboardData() error suppressed." ) return {} else: raise assert isinstance( plainText, unicode ), \ "GetClipboardData returned not-a-unicode object!!"
def GetRightMenuItems(self): # Just override parents ret = [] flags = 0 ret.append((flags, win32ui.ID_EDIT_UNDO, '&Undo')) ret.append(win32con.MF_SEPARATOR) ret.append((flags, win32ui.ID_EDIT_CUT, 'Cu&t')) ret.append((flags, win32ui.ID_EDIT_COPY, '&Copy')) start, end = self.GetSel() if start != end: ret.append((flags, ID_EDIT_COPY_CODE, 'Copy code without prompts')) if win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_UNICODETEXT): ret.append( (flags, ID_EDIT_EXEC_CLIPBOARD, 'Execute python code from clipboard')) ret.append((flags, win32ui.ID_EDIT_PASTE, '&Paste')) ret.append(win32con.MF_SEPARATOR) ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, '&Select all')) ret.append((flags, win32ui.ID_EDIT_SELECT_BLOCK, 'Select &block')) ret.append((flags, win32ui.ID_VIEW_WHITESPACE, "View &Whitespace")) return ret
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
def SendToRPy(aString): # backup the clipboard content (if text) w.OpenClipboard(0) if w.IsClipboardFormatAvailable(w.CF_TEXT): cdata = w.GetClipboardData() else: cdata = None w.CloseClipboard() finalString = aString.decode("latin-1") sleepTime = float(vim.eval("g:vimrplugin_sleeptime")) w.OpenClipboard(0) w.EmptyClipboard() w.SetClipboardText(finalString) w.CloseClipboard() shell = win32com.client.Dispatch("WScript.Shell") ok = shell.AppActivate("R Console") if ok: time.sleep(sleepTime) shell.SendKeys("^v") time.sleep(sleepTime) else: vim.command("call RWarningMsg('Is R running?')") time.sleep(1)
def main(window): try: import win32clipboard except: window.dialogCritical( "Cannot import win32clipboard", "pywin32 needs to be installed to use this\n(pip install pypiwin32)" ) return False if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT): win32clipboard.OpenClipboard() clipboard = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() if clipboard.startswith("'") or clipboard.startswith('"'): clipboard = clipboard[1:] if clipboard.endswith("'") or clipboard.endswith('"'): clipboard = clipboard[:-1] win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(clipboard) win32clipboard.CloseClipboard() return True
def is_clipboard_format_available(format): ERROR = 0 try: assert type(format) is str or type(format) is int except: ERROR = 1 if ERROR: raise unknown_clipboard_format_given(format) if type(format) is str: if format not in clipboard_formats_str: raise unknown_clipboard_format_given(format) else: return bool(win32clipboard.IsClipboardFormatAvailable( clipboard_formats_int[clipboard_formats_str.index(format)])) else: return bool(win32clipboard.IsClipboardFormatAvailable(format))
def get_clipboard_data(): winclip.OpenClipboard() if winclip.IsClipboardFormatAvailable(True): d = winclip.GetClipboardData(win32con.CF_TEXT) else: d = "" winclip.CloseClipboard() return d
def pasteW(): wc.OpenClipboard() if wc.IsClipboardFormatAvailable(win32con.CF_UNICODETEXT): out = wc.GetClipboardData(win32con.CF_UNICODETEXT) else: out = "" wc.CloseClipboard() return out
def readClip(): import win32clipboard import win32con win32clipboard.OpenClipboard() data = None if (win32clipboard.IsClipboardFormatAvailable(win32con.CF_UNICODETEXT)): data = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT) win32clipboard.CloseClipboard() return data
def __get(self): win32clipboard.OpenClipboard() if win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_UNICODETEXT): d = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) else: d = '' win32clipboard.CloseClipboard() return d
def __clipBoard_data(self): win32clipboard.OpenClipboard() if win32clipboard.IsClipboardFormatAvailable( win32clipboard.CF_TEXT): cb = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() return cb else: return ''
def get_clipboard(self): wcb.OpenClipboard() try: if wcb.IsClipboardFormatAvailable(wc.CF_UNICODETEXT): return wcb.GetClipboardData(wc.CF_UNICODETEXT).encode('utf-8') result = wcb.GetClipboardData() except TypeError: result = None wcb.CloseClipboard() return result
def get_clipboard_type(): """ Get the most recommended clipboard format, return None if we can't handle it """ win32clipboard.OpenClipboard() supported_cf = None for _format in SUPPORTED_CF: if win32clipboard.IsClipboardFormatAvailable(_format): supported_cf = _format break win32clipboard.CloseClipboard() return supported_cf
def clipboard_get(default=""): open_clipboard() result = default if win32clipboard.IsClipboardFormatAvailable(win32con.CF_TEXT): result = get_clipboard_data(win32con.CF_TEXT) win32clipboard.CloseClipboard() null = string.find(result, chr(0)) if null > 0: result = result[0:null] return result
def clipboard_get_UTF8(): open_clipboard() result = "" if win32clipboard.IsClipboardFormatAvailable(win32con.CF_UNICODETEXT): result = get_clipboard_data(win32con.CF_UNICODETEXT) win32clipboard.CloseClipboard() null = string.find(result, chr(0)) if null > 0: result = result[0:null] result = result.encode('utf-8') return result
def on_release(key): logging.warning('---> {0} released'.format(key)) # Turns off keylogger if key == keyboard.Key.esc: return False if key == keyboard.Key.enter: capture.capture() if key == keyboard.Key.ctrl_l: # activate ctrl_V() only if clipboard content is text if win32clipboard.IsClipboardFormatAvailable(1) == 1: ctrl_V()
def get_image_from_hdrop(): win32clipboard.OpenClipboard() if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_HDROP): files = win32clipboard.GetClipboardData(win32clipboard.CF_HDROP) img = None try: img = Image.open(files[0]) except IOError: pass win32clipboard.CloseClipboard() return img
def upload(): win32clipboard.OpenClipboard() try: if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB): data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB) else: print('clipboard does not contain an image in DIB format') sys.exit(1) finally: win32clipboard.CloseClipboard() bmih = BITMAPINFOHEADER() ctypes.memmove(ctypes.pointer(bmih), data, SIZEOF_BITMAPINFOHEADER) #这个验证有问题,会让正常的图片无法通过 #if bmih.biCompression != BI_BITFIELDS: # RGBA? #print('insupported compression type {}'.format(bmih.biCompression)) #sys.exit(1) bmfh = BITMAPFILEHEADER() ctypes.memset(ctypes.pointer(bmfh), 0, SIZEOF_BITMAPFILEHEADER) # zero structure bmfh.bfType = ord('B') | (ord('M') << 8) bmfh.bfSize = SIZEOF_BITMAPFILEHEADER + len(data) # file size SIZEOF_COLORTABLE = 0 bmfh.bfOffBits = SIZEOF_BITMAPFILEHEADER + SIZEOF_BITMAPINFOHEADER + SIZEOF_COLORTABLE #webp格式加载速度快,需要转化为webp bmp_filename = '%s.png'%GetNowTime() with open(bmp_filename, 'wb') as bmp_file: bmp_file.write(bmfh) bmp_file.write(data) bmp_file.close() #转换格式,经测试显示效果无异,webp所占空间仅为png的1% ,截图在这里:![](http://7xrrni.com1.z0.glb.clouddn.com/2016-11-08_17_24_41.png.webp?imageView2/0/w/800) im = Image.open(bmp_filename) f,ext = os.path.splitext(bmp_filename) webp_path = "%s.webp"%f im.save(webp_path, "WEBP") access_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" bucket_name = "xxxxxxxx" domain_name = "xxxxxxxxxxxxxxxxxxxxxxx" try: key = uploadImage(webp_path,access_key,secret_key,bucket_name) except Exception as e: print("发生错误:%s"%e) else: #print(os.getcwd()) os.remove("%s\%s"%(os.getcwd(),bmp_filename)) os.remove("%s\%s"%(os.getcwd(),webp_path)) #800表示如果图片长度超过800,则长度变为800,宽度自动缩放 set_clipboard("![](http://%s/%s?imageView2/0/w/800)"%(domain_name,key))
def wndProc(self, hwnd, msg, wParam, lParam): # 消息处理 if msg == WCON.WM_DESTROY: win32gui.PostQuitMessage(0) if msg == WCON.WM_DRAWCLIPBOARD: # 当剪切板更新的时候收到这个消息 utxt = None btxt = None try: # 有时候打不开会出异常 WCB.OpenClipboard() if WCB.IsClipboardFormatAvailable( WCON.CF_UNICODETEXT): # 判断是否有指定的内容 utxt = WCB.GetClipboardData(WCON.CF_UNICODETEXT) # if utxt.find('http') != -1: # utxt = utxt[utxt.find('http'):] if WCB.IsClipboardFormatAvailable(WCON.CF_TEXT): btxt = WCB.GetClipboardData(WCON.CF_TEXT) # if btxt.find('http') != -1: # btxt = btxt[btxt.find('http'):] WCB.CloseClipboard() except Exception as e: print("error:", e) # finally: ok = False # 依次尝试打印Unicode和字节码,ok是打印成功标志位 if utxt: try: if utxt.find('http') != -1: utxt = utxt[utxt.find('http'):] print("UNICODE:", utxt) ok = True except Exception as e: print(u'UNICODE打印失败:', e) if btxt and not ok: try: print("GBK:", btxt.decode('gbk')) except Exception as e: print(u'GBK打印失败:', e) return win32gui.DefWindowProc(hwnd, msg, wParam, lParam)
def get_image_filepath_from_clipboard(): try: wc.OpenClipboard() if wc.IsClipboardFormatAvailable(wc.CF_UNICODETEXT): upath_src = wc.GetClipboardData(wc.CF_UNICODETEXT) # It seems, with CF_UNICODETEXT, wc.GetClipboardData() returns not the raw bytes # from clipboard, but converted to Python 'unicode' type upath_src = re.sub(u'\u0000.*$', u'', upath_src, flags=re.DOTALL) # because there can be garbage chars after the NUL. # [2015-03-18] See my note: https://www.evernote.com/shard/s21/nl/2425275/256a14c6-542c-4e14-8fd8-040c70a4315a elif wc.IsClipboardFormatAvailable(CF_FileNameW): u16str = wc.GetClipboardData(CF_FileNameW) upath_src = unicode(u16str, 'utf-16LE') upath_src = upath_src.strip( u'\x00') # because there is a trailing NUL char elif wc.IsClipboardFormatAvailable(wc.CF_HDROP): # Using Everything 1.3.4.686, copying a single file generates a CF_HDROP content with one file in list, # so cope with this case. filelist = wc.GetClipboardData(wc.CF_HDROP) upath_src = filelist[ 0] # only get the first one, already a unicode string else: return None if len(upath_src) > 1024: return None if (upath_src[0].islower() or upath_src[0].isupper()) and (upath_src[1:3] == ':\\'): pass # looks like a fullpath else: return None # todo: May be more "filepath conformance" check except win32api.error: exit('Unexpected: Windows clipboard function Fail!') finally: wc.CloseClipboard() return upath_src
def get_clipboard(timeout: float = 1.0): st = time.time() while time.time() < st + timeout: if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT): try: win32clipboard.OpenClipboard() cdata = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() return cdata except: pass time.sleep(0.001) return ''