Python Forum
Get current app window handle and bring window to front
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get current app window handle and bring window to front
#1
I'm trying to set up a simple command line chat application between two computers on my home network. I have the server and client scripts working exactly the way I want except for one little thing. At least it should be little and I do not understand why it is so difficult.

I intend to leave the script running in a small window. When it receives a new message I want it to pop to the front. When I comment out the line that does this the script works. But when I enable the "to front" line it aborts with

Output:
Exception in thread Thread-2 (recv_message): Traceback (most recent call last): File "C:\Python\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\apps\chat\client.py", line 30, in recv_message win32gui.SetForegroundWindow(hwnd) pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')
I've tested the code for win32gui.SetForegroundWindow(hwnd) by starting two client apps and, from a python shell, running win32gui.SetForegroundWindow(hwnd) with (in turn) both of the handles. No problem. Until I enable the code in the client script. When I do that I get the exception. I am running Python 3.10.11 on Windows 11 Home.

Here is the client script.

import socket
import threading
import win32gui
import ctypes


host = 'jim-asus'
port = 1234
hwnd = ctypes.windll.user32.GetForegroundWindow()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((host, port))

print(f'Connected to the server. {hwnd=}')

def send_message():
    
    while True:
        message = input('')
        server.send(message.encode())

def recv_message():
    
    while True:
        message = server.recv(1024)
        print(">>", message.decode())
        print(f'set {hwnd=} to front')
        win32gui.SetForegroundWindow(hwnd)

send = threading.Thread(target=send_message)
recv = threading.Thread(target=recv_message)

send.start()
recv.start()
Reply
#2
Unless I am looking at the wrong win32gui, it looks like it hasn't been updated since 2017.
Perhaps, for simple application, switch tkinter or some other gui?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020