Oct-27-2023, 12:40 AM
(This post was last modified: Oct-27-2023, 12:40 AM by rjdegraff42.)
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
Here is the client script.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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() |