Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Terminal
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:
Python
  1  import socket
  2  import threading
  3  import win32gui
  4  import ctypes
  5  
  6  host = 'jim-asus'
  7  port = 1234
  8  hwnd = ctypes.windll.user32.GetForegroundWindow()
  9  
 10  server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 11  server.connect((host, port))
 12  
 13  print(f'Connected to the server. {hwnd=}')
 14  
 15  def send_message():
 16      
 17      while True:
 18          message = input('')
 19          server.send(message.encode())
 20  
 21  def recv_message():
 22      
 23      while True:
 24          message = server.recv(1024)
 25          print(">>", message.decode())
 26          print(f'set {hwnd=} to front')
 27          win32gui.SetForegroundWindow(hwnd)
 28  
 29  send = threading.Thread(target=send_message)
 30  recv = threading.Thread(target=recv_message)
 31  
 32  send.start()
 33  recv.start()


What I have tried:

pywin32, AutoItX, win32gui, pywinauto
Posted
Updated 27-Oct-23 4:24am
v4

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900