Last active
June 11, 2020 05:31
-
-
Save mo-han/0e6730b15e1f491a10236522880582d2 to your computer and use it in GitHub Desktop.
simple class for using clipboard in NT OS (Windows), supporting copied files (paths)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Clipboard: | |
| import win32clipboard as wcb | |
| cf_dict = {n.lstrip('CF_'): m for n, m in inspect.getmembers(wcb) if n.startswith('CF_')} | |
| def __enter__(self): | |
| self.open() | |
| return self | |
| def __exit__(self, exc_type, exc_val, exc_tb): | |
| self.close() | |
| def open(self): | |
| self.wcb.OpenClipboard() | |
| def close(self): | |
| self.wcb.CloseClipboard() | |
| def valid_format(self, x: str or int): | |
| """get valid clipboard format ('CF_*')""" | |
| if isinstance(x, int): | |
| pass | |
| elif isinstance(x, str): | |
| x = x.upper() | |
| if not x.startswith('x_'): | |
| x = 'CF_' + x | |
| x = getattr(self.wcb, x) | |
| else: | |
| raise TypeError("'{}' is not str or int".format(x)) | |
| return x | |
| def clear(self): | |
| return self.wcb.EmptyClipboard() | |
| def set(self, data, cf=wcb.CF_UNICODETEXT): | |
| cf = self.valid_format(cf) | |
| return self.wcb.SetClipboardData(cf, data) | |
| def set_text(self, text): | |
| return self.wcb.SetClipboardText(text) | |
| def get(self, cf=wcb.CF_UNICODETEXT): | |
| cf = self.valid_format(cf) | |
| if self.wcb.IsClipboardFormatAvailable(cf): | |
| data = self.wcb.GetClipboardData(cf) | |
| else: | |
| data = None | |
| return data | |
| def get_paths(self): | |
| """of copied files""" | |
| paths = self.get(self.wcb.CF_HDROP) | |
| if paths: | |
| return list(paths) | |
| else: | |
| return [] | |
| def get_all(self): | |
| d = {} | |
| for k, v in self.cf_dict.items(): | |
| d[k] = self.get(v) | |
| return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment