Search code examples
pythonpywin32

Drag and drop into other program


I would like to create an application for drag and drop to take a file into other application. For example, in my python window I would like take file and drop it in windows or photoshop. Is it possible in Python and need I use pywin32? For the moment I didn't find any information about this problem or just into window program path Thank you in advance


Solution

  • I do not have Windows, but from what I remember, you'll need to have a window's handle (either for the shell Window or for some graphical one e.g. WinForms or others). Then try to check the WM_DROPFILES message or better, ole2.h's RegisterDragDrop and via pDropTarget try to retrieve the sent path.

    For WM_DROPFILES you can take an inspiration from SDL2's codebase in SDL_windowsevents.c

        case WM_DROPFILES:
            {
                UINT i;
                HDROP drop = (HDROP) wParam;
                UINT count = DragQueryFile(drop, 0xFFFFFFFF, NULL, 0);
                for (i = 0; i < count; ++i) {
                    SDL_bool isstack;
                    UINT size = DragQueryFile(drop, i, NULL, 0) + 1;
                    LPTSTR buffer = SDL_small_alloc(TCHAR, size, &isstack);
                    if (buffer) {
                        if (DragQueryFile(drop, i, buffer, size)) {
                            char *file = WIN_StringToUTF8(buffer);
                            SDL_SendDropFile(data->window, file);
                            SDL_free(file);
                        }
                        SDL_small_free(buffer, isstack);
                    }
                }
                SDL_SendDropComplete(data->window);
                DragFinish(drop);
                return 0;
            }
            break;
    

    which uses WIN_WindowProc() in this manner:

    Initialize WNDCLASSEX struct:

    WNDCLASSEX wcex;
    // fill its members and this one for event handling:
    wcex.lpfnWndProc = WIN_WindowProc;
    

    then register it with RegisterClassEx(&wcex).

    Of course, that's just C/C++ code. You'll either need to find translated or otherwise linked members of the libraries in pywin32 or use something that can access the libraries in a way you need, such as ctypes or Cython.

    Other resources: