Search code examples
pythonwindowsclipboardpywin32

Get filename after a CTRL+C on a file with Windows Explorer


When you do Copy (CTRL+C) on a file, then in some programs (example: it works in the Windows Explorer address bar, also with Everything indexing software), when doing Paste (CTRL+V), the filename or directory name is pasted like text, like this: "d:\test\hello.txt".

I tried this:

  • CTRL+C on a file or folder in Windows Explorer
  • Run:

    import win32clipboard
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()
    print data
    

But I get this error:

TypeError: Specified clipboard format is not available

Question: how to retrieve the filename of a file that has been "copied" (CTRL+C) in the Windows Explorer?


Solution

  • The clipboard may contain more than one format. For example, when formatted text is copied from MS word, both the formatted text and the plain text will be in the clipboard, so that depending on the application into which you are pasting, the target application may take one or the other format, depending on what it supports.

    From MSDN:

    A window can place more than one clipboard object on the clipboard, each representing the same information in a different clipboard format. When placing information on the clipboard, the window should provide data in as many formats as possible. To find out how many formats are currently used on the clipboard, call the CountClipboardFormats function.

    Because of that, win32clipboard.GetClipboardData takes one argument: format, which is by default win32clipboard.CF_TEXT.

    When you call it without arguments, it raises error saying TypeError: Specified clipboard format is not available, because TEXT format is not in the clipboard.

    You can, instead, ask for win32clipboard.CF_HDROP format, which is "A tuple of Unicode filenames":

    import win32clipboard
    win32clipboard.OpenClipboard()
    filenames = win32clipboard.GetClipboardData(win32clipboard.CF_HDROP)
    win32clipboard.CloseClipboard()
    for filename in filenames:
        print(filename)
    

    See also MSDN doc for standard clipboard formats