I'm new to python and coding in general, but I'm building a "jukebox" software that will take an input from the user and open that song in spotify. I've got it working pretty well, but would like it to run without a monitor or mouse input, just the keyboard (like a regular jukebox).
As a result, I need the user input window to be brought to the foreground every time it asks for input. I've defined that process within the function 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)
I'm using that function within my program like this:
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
The site_login() function opens Chrome and logs in to spotify, thus putting that window on top. The first iteration of bring_to_front() in the while loop successfully puts the input window in the foreground and lets me type in a song code. However, once I've done that for the first time and Chrome has been brought to the foreground again (to open up a song), I get an error message on the second iteration of bring_to_front(). The problem is specifically with win32gui.SetForegroundWindow(handle). The error message I get is:
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')
I can't figure out why it works the first time, but won't continue to work after that. I did find this article which seems to reference the same problem. The solution says it works if you send an alt key first, but I couldn't figure out how to do that from his example. Like I said, I'm new to all of this. Any help would be appreciated. Thanks!