鱼C论坛

 找回密码
 立即注册
查看: 2419|回复: 7

[已解决]接收拖拽到其它窗口的文件路径

[复制链接]
发表于 2022-2-24 10:53:11 | 显示全部楼层 |阅读模式
10鱼币

想做一个无窗口后台程序,可以获取指定窗口的拖拽事件,得到拖拽文件路径
(只要是获取拖拽其它窗口的文件,所以窗口组件的拖拽事件self.setAcceptDrops(True)是不适应的)

import win32gui, win32ui, win32con
hwnd = win32gui.FindWindow(None, "Test Dialogs")#获取窗口句柄
win32gui.DragAcceptFiles(hwnd, True) #定义一个窗口句柄接受拖拽

以下找到的示例无效
wnd = win32ui.CreateWindowFromHandle(hwnd)
wnd.HookMessage(self.test, win32con.WM_DROPFILES)


请教有可以实现的方法吗?

谢谢啦!
最佳答案
2022-2-24 10:53:12
本帖最后由 hrpzcf 于 2022-3-11 12:13 编辑

看你还没解决,我按照楼上大佬的代码修改了做成模块了,你自己看看吧

(, 下载次数: 6)

下载附件,把里面三个文件解压至你项目里能import 到的地方,用法:
  1. import time

  2. from GouZi import *


  3. def test1():
  4.     # 实例化一个文件拖放事件钩子客户端
  5.     # 当然,你想直接调用dll也行,可导出的函数跟DragHookClient类里的函数同名
  6.     dh = DragHookClient()
  7.     print(f"启用钩子:{dh.HookDrag()}")  # 安装拖放事件钩子
  8.     print(f"钩子是否启用:{dh.IsHooked()}")  # 检查钩子是否已安装
  9.     count = 0
  10.     while count < 60:  # while True:
  11.         count += 1
  12.         if dh.HasNewDropFiles():  # 查询是否有新的拖放事件
  13.             print(dh.GetNewDropFiles())  # 获取新的拖放事件生成的路径列表
  14.         time.sleep(1)
  15.     dh.UnHookDrag()  # 程序结束不要忘记卸载钩子


  16. def test2():
  17.     with DragHookClient() as dh:
  18.         if dh.IsHooked():  # 检查钩子是否已安装
  19.             print("钩子已启用")
  20.         else:
  21.             print("钩子未启用")
  22.             return
  23.         count = 0
  24.         while count < 60:  # while True:
  25.             count += 1
  26.             if dh.HasNewDropFiles():  # 查询是否有新的拖放事件
  27.                 print(dh.GetNewDropFiles())  # 获取新的拖放事件生成的路径列表
  28.             time.sleep(1)


  29. if __name__ == "__main__":
  30.     # test1()
  31.     test2()
复制代码



GouZi.py
  1. import sys
  2. from ctypes import c_bool, c_wchar_p, windll
  3. from os import path

  4. __all__ = ["DragHookClient"]

  5. if sys.maxsize > 0xFFFFFFFF:
  6.     dllName = "GouZi_vc143_x64.dll"
  7. else:
  8.     dllName = "GouZi_vc143_x86.dll"
  9. rootPath = path.dirname(path.realpath(__file__))
  10. dllFullPath = path.join(rootPath, dllName)


  11. class DragHookClient:
  12.     """WIN全局文件拖放事件钩子客户端"""

  13.     def __init__(self):
  14.         self.__hook = windll.LoadLibrary(dllFullPath)
  15.         self.__hook.IsHooked.restype = c_bool
  16.         self.__hook.HasNewDropFiles.restype = c_bool
  17.         self.__hook.HookDrag.restype = c_bool
  18.         self.__hook.GetNewDropFiles.restype = c_wchar_p

  19.     def IsHooked(self) -> bool:
  20.         """检查是否已启用全局文件拖放事件钩子"""
  21.         return self.__hook.IsHooked()

  22.     def HasNewDropFiles(self) -> bool:
  23.         """检查是否有新的文件拖放事件"""
  24.         return self.__hook.HasNewDropFiles()

  25.     def UnHookDrag(self) -> None:
  26.         """停止全局文件拖放事件钩子"""
  27.         self.__hook.UnHookDrag()

  28.     def HookDrag(self) -> bool:
  29.         """启用全局文件拖放事件钩子"""
  30.         return self.__hook.HookDrag()

  31.     def GetNewDropFiles(self) -> list:
  32.         """以列表形式返回检测到的全局文件拖放事件的文件路径"""
  33.         string = self.__hook.GetNewDropFiles()
  34.         return [s for s in string.strip().split("\n") if s]

  35.     # def __del__(self) -> None:
  36.     #    self.__hook.UnHookDrag()

  37.     def __enter__(self) -> "DragHookClient":
  38.         self.__hook.HookDrag()
  39.         return self

  40.     def __exit__(self, excType, excValue, excTB) -> None:
  41.         self.__hook.UnHookDrag()
复制代码


Hook.c
  1. #include <Windows.h>
  2. #include <strsafe.h>

  3. #define MAX_STRLEN 131072
  4. #define LOCKER TEXT("j5u7ld6va0b489sj1y3k28r1n3b1")
  5. #define IDRAGFILE INFINITE

  6. typedef struct {
  7.     INT len;
  8.     TCHAR str[MAX_STRLEN];
  9. } cp_t;

  10. #pragma data_seg("shared")
  11. static BOOL hasNewDrops = FALSE;
  12. static cp_t dropedFiles = { 0 };
  13. static HHOOK hHookHnd = NULL;
  14. #pragma data_seg()
  15. #pragma comment(linker, "/section:shared,rws")

  16. static HINSTANCE hLibInst;

  17. BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) {
  18.     switch (reason) {
  19.     case DLL_PROCESS_ATTACH:
  20.         hLibInst = instance;
  21.     }
  22.     return TRUE;
  23. }

  24. static void TargetWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
  25.     switch (message) {
  26.     case WM_DROPFILES: {
  27.         HDROP hDrop = (HDROP)wParam;
  28.         UINT reqSize = 0;
  29.         TCHAR buffer[MAX_PATH];
  30.         UINT count = DragQueryFile(hDrop, IDRAGFILE, NULL, 0);
  31.         HANDLE hMutex = CreateMutex(NULL, FALSE, LOCKER);
  32.         if (!hMutex) break;
  33.         WaitForSingleObject(hMutex, INFINITE);
  34.         if (!hasNewDrops) {
  35.             hasNewDrops = TRUE;
  36.             dropedFiles.len = 0;
  37.             dropedFiles.str[0] = 0;
  38.         }
  39.         for (UINT i = 0; i < count; ++i) {
  40.             reqSize = DragQueryFile(hDrop, i, NULL, 0);
  41.             if (reqSize >= MAX_PATH)
  42.                 continue;
  43.             if (dropedFiles.len + reqSize + 1 >= MAX_STRLEN)
  44.                 break;
  45.             DragQueryFile(hDrop, i, buffer, MAX_PATH);
  46.             StringCchCat(dropedFiles.str, MAX_STRLEN, buffer);
  47.             StringCchCat(dropedFiles.str, MAX_STRLEN, TEXT("\n"));
  48.             dropedFiles.len += (reqSize + 1);
  49.         }
  50.         dropedFiles.str[dropedFiles.len] = 0;
  51.         ReleaseMutex(hMutex);
  52.         break;
  53.     }
  54.     }
  55. }

  56. static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam) {
  57.     switch (nCode) {
  58.     case HC_ACTION: {
  59.         MSG *pMsg = (MSG *)lParam;
  60.         TargetWndProc(pMsg->hwnd, pMsg->message, pMsg->wParam, pMsg->lParam);
  61.         break;
  62.     }
  63.     }
  64.     return CallNextHookEx(hHookHnd, nCode, wParam, lParam);
  65. }

  66. __declspec(dllexport) void UnHookDrag(void) {
  67.     if (hHookHnd)
  68.         UnhookWindowsHookEx(hHookHnd);
  69.     hHookHnd = NULL;
  70. }

  71. __declspec(dllexport) BOOL HookDrag(void) {
  72.     if (hHookHnd) return TRUE;
  73.     hHookHnd = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc, hLibInst, 0);
  74.     return hHookHnd != NULL;
  75. }

  76. __declspec(dllexport) BOOL IsHooked(void) {
  77.     return hHookHnd != NULL;
  78. }

  79. __declspec(dllexport) BOOL HasNewDropFiles(void) {
  80.     BOOL newDrops = FALSE;
  81.     if (!IsHooked()) return newDrops;
  82.     HANDLE hMutex = CreateMutex(NULL, FALSE, LOCKER);
  83.     if (!hMutex) return newDrops;
  84.     WaitForSingleObject(hMutex, INFINITE);
  85.     newDrops = hasNewDrops;
  86.     ReleaseMutex(hMutex);
  87.     return newDrops;
  88. }

  89. __declspec(dllexport) TCHAR *GetNewDropFiles(void) {
  90.     static TCHAR dropedTemp[MAX_STRLEN];
  91.     dropedTemp[0] = 0;
  92.     if (!IsHooked()) return dropedTemp;
  93.     HANDLE hMutex = CreateMutex(NULL, FALSE, LOCKER);
  94.     if (!hMutex) return dropedTemp;
  95.     WaitForSingleObject(hMutex, INFINITE);
  96.     hasNewDrops = FALSE;
  97.     if (dropedFiles.len > 0) {
  98.         StringCchCopy(dropedTemp, MAX_STRLEN, dropedFiles.str);
  99.         dropedFiles.len = 0;
  100.         dropedFiles.str[0] = 0;
  101.     }
  102.     ReleaseMutex(hMutex);
  103.     return dropedTemp;
  104. }
复制代码




@人造人


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-3-5 17:15:29 | 显示全部楼层
人造人 发表于 2022-3-1 02:36
现学现卖,耗时4天,^_^
就我所知,目前拖放文件有两种完全不同的方法
一种是通过消息机制,使用 WM_DROP ...

首先感谢你的回复及给出的建议,因为是想在python里做出最终效果

也不会C改PY,只能暂时用其它方式做测试,还不知道能不能行
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-1 23:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表