python+win32: detect window drag

99封情书 提交于 2021-02-08 05:39:15

问题


Is there a way to detect when a window that doesn't belong to my application is being dragged in windows using python/pywin32? I want to set it up so that when I drag a window whose title matches a pattern near the desktop edge, it snaps to the edge when the mouse is let go. I could write code to snap all windows with that title to the desktop whenever the mouse is released, but I want to only move the particular window that was being dragged.


回答1:


So far the only possible solution I see is to use SetWindowsHookEx. Pywin32 doesn't interface this, so I think I'll have to do something like this:

  • Write a C extension module. It has a function like setCallback which takes a python function to be called when the drag event happens.
  • Write a C DLL that contains the actual hook into windows. This DLL will somehow have to call the python function that is currently set.

I'm not sure how to do these, or if it's correct, though..




回答2:


pyHook seems to have done some of the work necessary, as it's hooked keyboard and mouse events. What I will probably do is keep a constant record of all the windows I care about, along with their positions. Then, on mouse up, I'll detect if any of the windows moved, and if so, and it's near where the mouse was let go, on the title-bar, I'll assume it was dragged there and snap it. Code to hook follows.

import pyHook

def mouseUp(event):
    if event.Injected: return True

    print "Mouse went up"
    return True

hookManager = pyHook.HookManager()
hookManager.MouseLeftUp = mouseUp
hookManager.HookMouse()

You also need a main loop, which I have since I'm using gtk already, or you can do:

import pythoncom
pythoncom.PumpMessages()


来源:https://stackoverflow.com/questions/3753612/pythonwin32-detect-window-drag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!