虚拟机有QQ消息时宿主机自动弹窗提示

因为是检测窗口实现的,所以要求设置会话窗口自动弹出,而且看完消息就把QQ消息窗口关掉。。。

虚拟机端

#! /usr/bin/env python
# -*- coding: utf-8 -*-

from win32gui import *
import time
import socket

HOST = '192.168.0.126'#宿主机IP地址
PORT = 8001

def get_QQ_titles(hwnd, mouse):
    if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
        if GetClassName(hwnd) == 'TXGuiFoundation':  # TXGuiFoundation 是所有QQ窗口的类名
            text=GetWindowText(hwnd)
            if text:
                current_QQ_titles.add(text)

def send_message(): # 通知宿主机
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.send('new_msg')
    data = s.recv(10)
    print data

last_QQ_titles = set() # 上一次所有可见QQ窗口的 title 字符串集合
current_QQ_titles = set() # 当前所有可见QQ窗口的 title 字符串集合
last_foreground_window_class_name = '' # 上一个 foreground window 的类名
while True:
    current_QQ_titles = set()
    EnumWindows(get_QQ_titles, 0) # 遍历当前可见的QQ窗口
    try:
        foreground_window = GetForegroundWindow()
        foreground_window_text = GetWindowText(foreground_window)
        foreground_window_class_name = GetClassName(foreground_window)
    except Exception,e:
        print('catch exception')
    if last_QQ_titles != current_QQ_titles 
      and len(last_QQ_titles) < len(current_QQ_titles) 
        and (last_foreground_window_class_name != foreground_window_class_name 
          or (last_foreground_window_class_name == foreground_window_class_name 
            and foreground_window_text != 'QQ')):
        print 'got new message'
        send_message()
    last_QQ_titles = current_QQ_titles
    last_foreground_window_class_name = foreground_window_class_name
    time.sleep(1)

宿主机端

 1 #encoding=utf-8
 2 import Tkinter as tk
 3 import socket
 4 
 5 def create_message_dialog():
 6     top = tk.Tk()
 7     top.title("QQ Message")
 8     top.geometry('400x400')
 9     labelHello = tk.Label(top, text = "You've got new QQ messages.")
10     labelHello.pack()
11     top.mainloop()
12 
13 HOST = '192.168.0.126'
14 PORT = 8001
15 
16 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
17 s.bind((HOST, PORT))
18 s.listen(1)
19 
20 print 'Server start at: %s:%s' %(HOST, PORT)
21 print 'wait for connection...'
22 
23 while True:
24     conn, addr = s.accept()
25     print 'Connected by ', addr
26     data = conn.recv(10)
27     print data
28     if data=='new_msg':
29         create_message_dialog()
30     conn.send("recv")
31     conn.close()

END

2017.8.17 19:58

原文地址:https://www.cnblogs.com/maxuewei2/p/7384122.html