如题,想通过 handle 让别程序关闭我编译为 exe 的程序,
原理是通过向 handle 发送关闭信号,程序检测到,就执行相关代码,顺便想看看一个程序是如何通过句柄控制其他程序的,暂时不使用其他进程间通讯技术
hinst = win32gui.GetModuleHandle(None)
hWindow = pywintypes.HANDLE()
这两个获取的句柄不一样,使用 spyxx 获取句柄后,手动发送信号也没反应,不知道是什么原因,在此请教,不胜感激。
代码如下
# -*- coding: utf-8 -*-
import time,pywintypes
import threading
from ctypes import *
from ctypes.wintypes import *
import win32con,win32gui
user32 = windll.user32
class ListenThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
#保存线程 ID
# self.ident = threading._get_ident()
msg = MSG()
#创建线程消息队列
user32.PeekMessageW(byref(msg), None, win32con.WM_USER,win32con.WM_USER, win32con.PM_NOREMOVE)
self.hinst = win32gui.GetModuleHandle(None)
print(self.hinst)
hWindow = pywintypes.HANDLE()
print("hWindow:", hWindow)
#消息循环
while True:
user32.GetMessageW(byref(msg), None, 0, 0)
if msg.message == win32con.WM_QUIT:
print ('thread quit' )
break
elif msg.message == win32con.WM_USER + 779:
print( 'I get it' )
else:
print("ddd")
time.sleep(1)
user32.TranslateMessage(byref(msg))
user32.DispatchMessageW(byref(msg))
print ('create thread' )
hThread = ListenThread()
print ('start thread')
hThread.start()
for i in range(5):
time.sleep(1)
user32.PostMessageW(hThread.hinst, win32con.WM_USER + 779, 0, 0)
print ("ddddd")
else:
user32.PostThreadMessageW(hThread.hinst, win32con.WM_QUIT, 0, 0)