-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
97 lines (78 loc) · 2.7 KB
/
main.py
File metadata and controls
97 lines (78 loc) · 2.7 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import pystray
from PIL import Image
import threading
import time
import sys
import ctypes
import win32con
if sys.platform == 'win32':
class Win32PystrayIcon(pystray.Icon):
WM_LBUTTONUP = 0x0202
WM_LBUTTONDBLCLK = 0x0203
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.action = kwargs['action']
def _on_notify(self, wparam, lparam):
super()._on_notify(wparam, lparam)
if lparam == self.WM_LBUTTONUP:
if self.action:
self.action(self)
pystray.Icon = Win32PystrayIcon
class SystemTrayApp:
def __init__(self, name='TestApp', image='app.png'):
self.name = name
self.hwnd = self._get_console_handle()
try:
image = Image.open(image)
except FileNotFoundError:
image = Image.new('RGB', (64, 64), 'white')
self.icon = pystray.Icon(
name=self.name,
icon=image,
title='Click to Toggle Console',
action=self.toggle_console
)
self.icon.menu = pystray.Menu(
pystray.MenuItem(self.get_toggle_text, self.toggle_console),
pystray.Menu.SEPARATOR,
pystray.MenuItem('Exit', self.exit_app)
)
def _get_console_handle(self):
if sys.platform != 'win32':
return None
return ctypes.windll.kernel32.GetConsoleWindow()
def _is_console_visible(self):
if sys.platform != 'win32' or not self.hwnd:
return False
return ctypes.windll.user32.IsWindowVisible(self.hwnd)
def toggle_console(self, icon):
if sys.platform != 'win32':
return
if not self.hwnd:
print("Error: Could not get console window handle.")
return
visible = self._is_console_visible()
if visible:
ctypes.windll.user32.ShowWindow(self.hwnd, win32con.SW_HIDE)
print("Console hidden via icon click.")
else:
ctypes.windll.user32.ShowWindow(self.hwnd, win32con.SW_SHOW)
ctypes.windll.user32.SetForegroundWindow(self.hwnd)
print("Console shown via icon click.")
def get_toggle_text(self, item):
if self._is_console_visible():
return 'Hide Console (Visible)'
return 'Show Console (Hidden)'
def exit_app(self, icon, item):
print("Exiting application...")
icon.stop()
def run(self):
print("PyTray application started.")
self.icon.run_detached()
if __name__ == '__main__':
app = SystemTrayApp(
name='pystray-training',
image='app.png'
)
app.run()