-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_program_launcher.txt
More file actions
411 lines (314 loc) · 11.9 KB
/
simple_program_launcher.txt
File metadata and controls
411 lines (314 loc) · 11.9 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# Mouse Launcher
**Minimalist app launcher triggered by simultaneous Left+Right mouse click.**
Zero external dependencies - pure Python standard library (tkinter + ctypes).



---
## Features
- **L+R Click Trigger** - Press both mouse buttons simultaneously to show launcher
- **Instant Access** - Popup appears at cursor position
- **Hot Reload** - Edit `config.json` anytime, changes apply on next trigger
- **Keyboard Shortcuts** - Press 1-9 to launch items quickly
- **Click Outside to Close** - Or press Escape
- **Separators** - Organize items into groups
- **Auto Start** - Optional Windows startup integration
---
## Quick Start
```bash
# Run directly
pythonw launcher.pyw
# Or with visible console (for debugging)
python launcher.pyw
```
**Usage:** Press **Left + Right mouse buttons** together anywhere on screen.
---
## Configuration
Edit `config.json` to customize your launcher:
```json
{
"items": [
{"name": "My App", "path": "C:\\path\\to\\app.exe", "icon": "🚀"},
{"name": "Project Folder", "path": "D:\\Projects", "icon": "📁"},
{"name": "─────────────", "path": "", "icon": " ", "separator": true},
{"name": "Notepad", "path": "notepad.exe", "icon": "📝"},
{"name": "Calculator", "path": "calc.exe", "icon": "🔢"}
]
}
```
### Item Properties
| Property | Required | Description |
|----------|----------|-------------|
| `name` | Yes | Display name |
| `path` | Yes | Full path to exe/file/folder, or system command |
| `icon` | No | Emoji or character (default: ▶) |
| `separator` | No | Set `true` for non-clickable divider line |
---
## Auto Start (Windows)
### Method 1: VBS Script (Silent, No Console Flash)
1. Press `Win+R`, type `shell:startup`, press Enter
2. Create `MouseLauncher.vbs` with this content:
```vbs
' MouseLauncher.vbs - Silent startup script
' Launches pythonw without any visible window
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "pythonw ""D:\path\to\launcher.pyw""", 0, False
```
**How it works:**
- `WScript.Shell.Run` executes a command
- `pythonw` runs Python without console window
- Second parameter `0` = hidden window
- `False` = don't wait for completion
### Method 2: BAT File (Simple, Brief Console Flash)
Create `MouseLauncher.bat` in `shell:startup`:
```bat
@echo off
start "" pythonw "D:\path\to\launcher.pyw"
```
**Note:** BAT shows a brief black console flash on startup. VBS method is cleaner.
### Startup Folder Location
```
C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
```
Or access via: `Win+R` → `shell:startup`
---
## How It Works
### Architecture
```
┌─────────────────────────────────────────────────────┐
│ MouseLauncher (Main Controller) │
│ ├── Polls mouse state every 30ms via Windows API │
│ ├── Detects L+R simultaneous press │
│ └── Manages popup lifecycle │
├─────────────────────────────────────────────────────┤
│ LauncherPopup (UI) │
│ ├── Borderless tkinter window │
│ ├── Loads config.json fresh on each show │
│ └── Click-outside detection with debounce │
└─────────────────────────────────────────────────────┘
```
### Key Technical Decisions
**1. Polling vs Hooks**
```python
# Using GetAsyncKeyState polling (simple, reliable)
left = user32.GetAsyncKeyState(VK_LBUTTON) & 0x8000
right = user32.GetAsyncKeyState(VK_RBUTTON) & 0x8000
# Why not SetWindowsHookEx?
# - Hooks require message pump in separate thread
# - 64-bit type issues with ctypes callbacks
# - Polling at 30ms is imperceptible and CPU-light
```
**2. Click-Outside Detection Challenge**
```python
# Problem: L+R triggers popup, but L is still held
# → Immediately detected as "click outside" → closes instantly
# Solution: Wait for BOTH buttons to release first
if not self._buttons_released:
if not left and not right:
self._buttons_released = True # Now start listening
return # Keep waiting
```
**3. Hot Reload Config**
```python
def show(self, x, y):
items = self._load_items() # Fresh load every time!
# No restart needed when editing config.json
```
**4. Launch Strategy**
```python
if os.path.exists(path):
os.startfile(path) # Files, folders, URLs
else:
subprocess.Popen(path, shell=True) # System commands
```
---
## Full Source Code
<details>
<summary>launcher.pyw (~230 lines)</summary>
```python
"""
Mouse Launcher - L+R Click to Launch
Minimalist launcher with zero external dependencies
"""
import ctypes
import json
import os
import subprocess
import time
import tkinter as tk
from pathlib import Path
# Windows API for mouse state detection
user32 = ctypes.windll.user32
VK_LBUTTON, VK_RBUTTON = 0x01, 0x02
class POINT(ctypes.Structure):
"""Windows POINT structure for cursor position"""
_fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
CONFIG_FILE = Path(__file__).parent / "config.json"
POLL_MS = 30 # Mouse polling interval
class LauncherPopup:
"""Floating popup window with pinned items"""
BG = "#1a1a2e" # Dark background
FG = "#ffffff" # White text
HOVER = "#2d2d44" # Hover highlight
ITEM_HEIGHT = 36
WIDTH = 240
def __init__(self, root, on_close):
self.root = root
self.on_close = on_close
self.win = None
self._closing = False
def _load_items(self):
"""Load items fresh from config (hot reload support)"""
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return json.load(f).get("items", [])
except:
pass
# Fallback defaults
return [
{"name": "Notepad", "path": "notepad.exe", "icon": "📝"},
{"name": "Explorer", "path": "explorer.exe", "icon": "📁"},
]
def show(self, x, y):
if self.win or self._closing:
return
items = self._load_items()
# Create borderless, always-on-top window
self.win = tk.Toplevel(self.root)
self.win.overrideredirect(True)
self.win.attributes("-topmost", True)
self.win.attributes("-alpha", 0.95)
self.win.configure(bg=self.BG)
# Position at cursor, keep on screen
height = len(items) * self.ITEM_HEIGHT + 16
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
x = min(x, screen_w - self.WIDTH - 10)
y = min(y, screen_h - height - 40)
self.win.geometry(f"{self.WIDTH}x{height}+{x}+{y}")
# Build item list
frame = tk.Frame(self.win, bg=self.BG)
frame.pack(fill="both", expand=True, padx=8, pady=8)
for i, item in enumerate(items):
self._create_item(frame, item, i)
self.win.bind("<Escape>", lambda e: self.hide())
self.win.focus_force()
# Start click-outside detection after buttons released
self._buttons_released = False
self.win.after(50, self._check_click_outside)
def _create_item(self, parent, item, index):
icon = item.get("icon", "▶")
name = item.get("name", "Unknown")
path = item.get("path", "")
is_sep = item.get("separator", False)
if is_sep:
# Non-clickable separator line
lbl = tk.Label(parent, text=f" {name}", font=("Segoe UI", 9),
bg=self.BG, fg="#555555", anchor="center", pady=2)
lbl.pack(fill="x", pady=0)
return
# Clickable item
lbl = tk.Label(parent, text=f" {icon} {name}", font=("Segoe UI", 11),
bg=self.BG, fg=self.FG, anchor="w", padx=8, pady=4,
cursor="hand2")
lbl.pack(fill="x", pady=2)
# Hover effects
lbl.bind("<Enter>", lambda e: lbl.configure(bg=self.HOVER))
lbl.bind("<Leave>", lambda e: lbl.configure(bg=self.BG))
lbl.bind("<Button-1>", lambda e: self._launch(path))
# Keyboard shortcut (1-9)
if index < 9:
self.win.bind(str(index + 1), lambda e, p=path: self._launch(p))
def _launch(self, path):
self.hide()
if path:
try:
if os.path.exists(path):
os.startfile(path)
else:
subprocess.Popen(path, shell=True)
except Exception as e:
print(f"Launch error: {e}")
def _check_click_outside(self):
if not self.win or self._closing:
return
left = user32.GetAsyncKeyState(VK_LBUTTON) & 0x8000
right = user32.GetAsyncKeyState(VK_RBUTTON) & 0x8000
# Wait for trigger buttons to release first
if not self._buttons_released:
if not left and not right:
self._buttons_released = True
self.win.after(50, self._check_click_outside)
return
# Detect fresh left click outside window
if left and not right:
pt = POINT()
user32.GetCursorPos(ctypes.byref(pt))
try:
wx, wy = self.win.winfo_rootx(), self.win.winfo_rooty()
ww, wh = self.win.winfo_width(), self.win.winfo_height()
if not (wx <= pt.x <= wx + ww and wy <= pt.y <= wy + wh):
self.hide()
return
except tk.TclError:
pass
if self.win:
self.win.after(50, self._check_click_outside)
def hide(self):
if self._closing:
return
self._closing = True
if self.win:
try:
self.win.destroy()
except:
pass
self.win = None
# Debounce before allowing next popup
self.root.after(300, self._finish_close)
def _finish_close(self):
self._closing = False
self.on_close()
class MouseLauncher:
"""Main controller - polls mouse and manages popup"""
def __init__(self):
self.root = tk.Tk()
self.root.withdraw() # Hide root window
self.popup = LauncherPopup(self.root, self._on_popup_close)
self._popup_shown = False
self._both_were_up = True
self._last_trigger = 0
def _poll_mouse(self):
"""Check for L+R simultaneous press"""
left = user32.GetAsyncKeyState(VK_LBUTTON) & 0x8000
right = user32.GetAsyncKeyState(VK_RBUTTON) & 0x8000
if left and right:
now = time.time()
if self._both_were_up and not self._popup_shown:
if now - self._last_trigger > 0.5: # Debounce 500ms
self._both_were_up = False
self._last_trigger = now
pt = POINT()
user32.GetCursorPos(ctypes.byref(pt))
self._show_popup(pt.x, pt.y)
elif not left and not right:
self._both_were_up = True
self.root.after(POLL_MS, self._poll_mouse)
def _show_popup(self, x, y):
self._popup_shown = True
self.popup.show(x, y)
def _on_popup_close(self):
self._popup_shown = False
def run(self):
self.root.after(100, self._poll_mouse)
self.root.mainloop()
if __name__ == "__main__":
MouseLauncher().run()
```
</details>
---
## License
MIT License - Use freely, modify as needed.
---
*Built with Python, zero dependencies, maximum simplicity.*