我正在使用 ctypes 在 python 中制作弹出窗口,我正在尝试制作一个程序,在屏幕的随机位置创建 50 个弹出窗口,但是我已经使用线程使 50 个弹出窗口同时出现,但它全部出现在中心看起来有点像一个弹出窗口。请帮帮我。 我正在使用的代码
import ctypes
import threading
# An included library with Python install.
def Mbox(title, text, style):
return ctypes.windll.user32.MessageBoxW(0, text, title, style)
if __name__ =="__main__":
for i in range(20):
t =threading.Thread(target=Mbox, args=("title","message",1,))
t.start()
print("Done!")
我正在尝试让弹出窗口出现在随机位置,所以如果你也能帮助我解决这个问题,那将会非常有帮助:)
您调用 MessageBox 的方式(尽管它有效)是不正确的(在 [Python.Docs]: ctypes - 函数原型中作为示例给出)。
检查[SO]:通过 ctypes 从 Python 调用的 C 函数返回不正确的值(@CristiFati 的答案),了解使用 CTypes(调用函数)时的常见陷阱。
我记得不久前我遇到了同样的问题,似乎有一个解决方案(我当时没有测试):[SO]:How do I hook a ctypes.windll.user32.MessageBoxW by using ctypes .windll.user32.SetWindowsHookExW? (@CristiFati 的回答),所以我继续尝试实现它,但到目前为止,我没有运气,Python 进程在进入回调时崩溃。
然后,我直接从 C 尝试,一切似乎都正常,所以我创建了一个 Python 包装器,并将其上传到 [PyPI]:pyzdoc (
python -m pip install pyzdoc
)。code00.py:
import random
import sys
import threading
import pyzdoc
from pyzdoc import constants
def mbox(title, text, style):
x = random.randint(0, 1500)
y = random.randint(0, 900)
print(f"MessageBox at: {x}, {y}")
return pyzdoc.MessageBox(title, text, x=x, y=y, style=style)
def main(*argv):
for i in range(3):
t = threading.Thread(target=mbox, args=("Title", "Message", 1))
t.start()
pyzdoc.MessageBox("Title", "Final message", style=constants.MB_CANCELTRYCONTINUE | constants.MB_ICONSTOP | constants.MB_DEFBUTTON3)
if __name__ == "__main__":
print(
"Python {:s} {:03d}bit on {:s}\n".format(
" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32,
sys.platform,
)
)
rc = main(*sys.argv[1:])
print("\nDone.\n")
sys.exit(rc)