win32gui.SetForegroundWindow(handle)无法循环运行

时间:2019-07-02 17:36:52

标签: python python-3.x pywin32

我一般不熟悉python和编码,但是我正在构建一个“自动点唱机”软件,该软件将接受用户的输入并在Spotify中打开该歌曲。我已经使其运行良好,但希望它在没有监视器或鼠标输入的情况下仅在键盘(如常规自动点唱机)上运行。

因此,我需要在每次要求输入时将用户输入窗口置于前台。我已经在功能Bring_to_front()中定义了该过程。

def bring_to_front():
    global handle
    handle = win32gui.FindWindowEx(0,0,None,r'C:\WINDOWS\py.exe')
    print(handle)
    win32gui.SetForegroundWindow(handle)

我正在程序中使用该函数,如下所示:

def program():
    global driver
    driver = webdriver.Chrome()

    site_login()

    while True:
        global handle
        global s
        global new_track
        bring_to_front()
        song_request()
        close_extra_tabs()
        if s == '*':
            restart()
        if s == '':
            print('Song stopped')
        else:
            for x in song_list:
                if x[0] == s:
                    new_track = x[2]
                    play_song()
                    print('Playing your song.')
                    break
                elif x == 'not_found':
                    print('Song not found')
                    error_audio()
                    break
                else:
                    continue

site_login()函数将打开Chrome并登录以进行发现,从而将该窗口置于顶部。在while循环中,Bring_to_front()的第一次迭代成功地将输入窗口置于前台,并让我输入了一个歌曲代码。但是,一旦我第一次这样做,并且Chrome再次被带到前台(打开一首歌曲),我就在第二次调用put_to_front()时收到一条错误消息。该问题专门与win32gui.SetForegroundWindow(handle)有关。我收到的错误消息是:

Traceback (most recent call last):
  File "C:\Users\user1\Documents\Spotify Jukebox\Spotify Jukebox3.py", line 125, in <module>
    program()
  File "C:\Users\user1\Documents\Spotify Jukebox\Spotify Jukebox3.py", line 102, in program
    bring_to_front()
  File "C:\Users\user1\Documents\Spotify Jukebox\Spotify Jukebox3.py", line 62, in bring_to_front
    win32gui.SetForegroundWindow(handle)
pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')

我不知道为什么它第一次起作用,但此后将不再继续起作用。我确实找到了this文章,其中似乎提到了相同的问题。该解决方案说,如果您先发送一个alt键,它就可以工作,但是我无法从他的例子中弄清楚该怎么做。就像我说的那样,我是这一切的新手。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了最奇怪的解决方案之一-在每次调用setWindowForeground之前,先虚拟按下alt。

我用pyautogui做到了。在同一代码中的两个后续调用之间插入以下行

pyautogui.press("alt")