I am trying to build a program that makes an announcement whenever you change language on your keyboard and whenever you change the case state.
The main issue i have is that it annnounces in the start and then whenever i change the language or case state ( upper/lower ) it doesn’t continue to announce.
Would appreciate any help or insights.
import pyttsx3
import ctypes
import win32api
import threading
import time
# Initialize text-to-speech engine
engine = pyttsx3.init()
# Initialize global variables for current language and case
current_language = None
current_case_state = None
# Function to get the current keyboard layout
def get_keyboard_language():
try:
user32 = ctypes.WinDLL('user32', use_last_error=True)
curr_window = user32.GetForegroundWindow()
thread_id = user32.GetWindowThreadProcessId(curr_window, 0)
klid = user32.GetKeyboardLayout(thread_id)
language_id = klid & (2 ** 16 - 1)
# Language mapping based on primary language identifier
languages = {
0x0409: "English", # English (US)
0x0C0C: "French", # French (Canada)
0x0407: "German", # German (Germany)
0x0410: "Italian", # Italian (Italy)
0x0A0A: "Spanish", # Spanish (Spain)
0x0408: "Greek", # Greek (Greece)
# Add more language codes if needed
}
return languages.get(language_id, "Unknown")
except Exception as e:
print(f"Error in get_keyboard_language: {str(e)}")
return "Unknown"
# Function to check if caps lock is on
def is_capslock_on():
try:
return win32api.GetKeyState(0x14) == 1
except Exception as e:
print(f"Error in is_capslock_on: {str(e)}")
return False
# Function to announce the language and case
def announce_language_case():
global current_language, current_case_state
try:
while True:
language = get_keyboard_language()
case_state = is_capslock_on()
case = "uppercase" if case_state else "lowercase"
if language != current_language or case_state != current_case_state:
current_language = language
current_case_state = case_state
print(announcement) # For debugging purposes
engine.say(announcement)
engine.runAndWait()
time.sleep(0.1) # Check every 0.1 seconds
except Exception as e:
print(f"Error in announce_language_case: {str(e)}")
# Start a thread to announce language and case changes
thread = threading.Thread(target=announce_language_case)
thread.daemon = True
thread.start()
# Keep the main thread running
try:
while True:
time.sleep(1) # Keep the main thread alive
except KeyboardInterrupt:
print("Stopping...")
New contributor