python设置窗口焦点

# coding:utf-8
import time
import psutil
import win32gui,win32process,win32con,win32com.client

class setf():
    def __init__(self):
        self.gamename='SuperStack.exe'
        self.shell=win32com.client.Dispatch("WScript.Shell")
        self.dll=CDLL("user32.dll")

    def setfocus(self):
        pid=self.get_pid_for_pname(self.gamename)
        if pid:
            for hwnd in self.get_hwnds_for_pid(pid):
                self.shell.SendKeys('%')
                self.dll.LockSetForegroundWindow(2)
                if self.dll.IsIconic(hwnd):
                    win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
                self.dll.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,0,0,win32con.SWP_NOSIZE|win32con.SWP_NOMOVE)
                self.dll.SetForegroundWindow(hwnd)
                self.dll.SetActiveWindow(hwnd)

    def get_pid_for_pname(self,processName):
        pids=psutil.pids()#获取主机所有的PID
        for pid in pids:#对所有PID进行循环
            p=psutil.Process(pid)#实例化进程对象
            if p.name()==processName:#判断实例进程名与输入的进程名是否一致(判断进程是否存活)
                return pid#返回
        return 0

    def get_hwnds_for_pid(self,pid):
        def callback (hwnd, hwnds):
            if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
                _,found_pid=win32process.GetWindowThreadProcessId(hwnd)
                if found_pid==pid:
                    hwnds.append(hwnd)
                return True
        hwnds=[]
        win32gui.EnumWindows(callback, hwnds)
        print hwnds
        return hwnds

if __name__ == '__main__':
    sf=setf()
    while True:
        time.sleep(3)
        try:
            sf.setfocus()
        except Exception,e:
            print e

网上找到的设置窗口焦点的文章只有win32gui.SetForegroundWindow(hwnd)一句,但是实际上,生成exe文件后,当焦点在桌面或者文件夹上,设置焦点会失败。翻了下C#和C的文章,调用user32.dll设置,主要语句如下

                self.shell.SendKeys('%')
                self.dll.LockSetForegroundWindow(2)
                if self.dll.IsIconic(hwnd):
                    win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
                self.dll.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,0,0,win32con.SWP_NOSIZE|win32con.SWP_NOMOVE)
                self.dll.SetForegroundWindow(hwnd)
                self.dll.SetActiveWindow(hwnd)

设置焦点没有再出现失败的情况。

 

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_32126137

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值