-
Notifications
You must be signed in to change notification settings - Fork 3
/
windows.py
526 lines (432 loc) · 14.7 KB
/
windows.py
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Windows related utilities.
"""
import win32gui
import win32con
import win32api
import win32process
import win32security
from win32gui import *
#from win32con import SW_RESTORE, SW_SHOWMINIMIZED, SW_SHOW
from win32con import *
from win32api import (
GetCurrentThreadId
)
from win32process import (
AttachThreadInput
)
from ctypes import *
import ctypes
import ctypes.wintypes
from ctypes import (
POINTER,
Structure
)
from ctypes.wintypes import (
DWORD,
LONG,
WORD,
BYTE,
RECT,
UINT,
ATOM
)
from pywingui.winuser import MAKEINTRESOURCE
from PyQt4.QtGui import QPixmap, QImage
from PyQt4.QtCore import Qt
import logging
import win32com.client
import logging
class tagTITLEBARINFO(Structure):
pass
tagTITLEBARINFO._fields_ = [
('cbSize', DWORD),
('rcTitleBar', RECT),
('rgstate', DWORD * 6),
]
PTITLEBARINFO = POINTER(tagTITLEBARINFO)
LPTITLEBARINFO = POINTER(tagTITLEBARINFO)
TITLEBARINFO = tagTITLEBARINFO
ASFW_ANY = -1
GetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId
AllowSetForegroundWindow = windll.user32.AllowSetForegroundWindow
#win32gui.SystemParametersInfo(
#win32con.SPI_SETFOREGROUNDLOCKTIMEOUT,
#0,
#win32con.SPIF_SENDWININICHANGE | win32con.SPIF_UPDATEINIFILE
#)
def SetForegroundWindowInternal(hWnd):
if not IsWindow(hWnd):
return
# relation time of SetForegroundWindow lock
lockTimeOut = 0
hCurrWnd = GetForegroundWindow()
dwThisTID = GetCurrentThreadId()
dwCurrTID = GetWindowThreadProcessId(hCurrWnd, 0)
# we need to bypass some limitations from Microsoft :)
if dwThisTID != dwCurrTID:
AttachThreadInput(dwThisTID, dwCurrTID, TRUE)
SystemParametersInfo(
SPI_SETFOREGROUNDLOCKTIMEOUT,0,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE)
AllowSetForegroundWindow(ASFW_ANY)
SetForegroundWindow(hWnd)
if dwThisTID != dwCurrTID:
AttachThreadInput(dwThisTID, dwCurrTID, FALSE)
import wmi
c = wmi.WMI()
def get_app_path(hwnd):
"""Get applicatin path given hwnd."""
try:
_, pid = win32process.GetWindowThreadProcessId(hwnd)
for p in c.query('SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
exe = p.ExecutablePath
break
except:
return None
else:
return exe
def get_app_name(hwnd):
"""Get applicatin filename given hwnd."""
try:
_, pid = win32process.GetWindowThreadProcessId(hwnd)
for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
exe = p.Name
break
except:
return None
else:
return exe
def AdjustPrivilege(priv, enable = 1):
# Get the process token.
flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY
htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
# Get the ID for the system shutdown privilege.
id = win32security.LookupPrivilegeValue(None, priv)
# Now obtain the privilege for this process.
# Create a list of the privileges to be added.
if enable:
newPrivileges = [(id, win32con.SE_PRIVILEGE_ENABLED)]
else:
newPrivileges = [(id, 0)]
# and make the adjustment.
win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
def elevate():
import os
import win32security
pid = os.getpid()
phandle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
token_handle=win32security.OpenProcessToken(phandle,win32con.TOKEN_ALL_ACCESS)
if token_handle==0:
print('提取令牌失败')
else:
Luid=win32security.LookupPrivilegeValue(None,win32security.SE_DEBUG_NAME)
if Luid==0:
print('Luid获取失败')
else:
new_token_pricileges=[(Luid,win32security.SE_PRIVILEGE_ENABLED)]
i=win32security.AdjustTokenPrivileges(token_handle,0,new_token_pricileges)
if i==0:
print('提权失败')
else:
print('succ')
win32api.CloseHandle(token_handle)
def goto(hwnd):
#_, pid = win32process.GetWindowThreadProcessId(hwnd)
#shell = win32com.client.Dispatch('WScript.Shell')
#shell.AppActivate(pid)
#shell.SendKeys(r'(% )x')
_old(hwnd)
def _old(hwnd):
"""So ugly here..."""
if not win32gui.IsWindow(hwnd):
return
fgwin = win32gui.GetForegroundWindow()
fg, fp = win32process.GetWindowThreadProcessId(fgwin)
current = win32api.GetCurrentThreadId()
try:
attached = False
if current != fg and fg:
try:
attached = win32process.AttachThreadInput(fg, current, True)
except:
pass
#AllowSetForegroundWindow(ASFW_ANY)
_, showCmd, _, _, _ = win32gui.GetWindowPlacement(hwnd)
# to show window owned by admin process when running in user process
# see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
# for details
if showCmd == SW_SHOWMINIMIZED:
#win32gui.ShowWindow(hwnd, SW_RESTORE)
win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
else:
#win32gui.ShowWindow(hwnd, SW_SHOW)
win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SW_SHOW, 0)
for fn in [
win32gui.BringWindowToTop,
win32gui.SetForegroundWindow,
win32gui.SetActiveWindow,
win32gui.SetFocus
]:
try:
fn(hwnd)
except Exception as e:
logging.error(str(e))
except Exception as e:
logging.error(str(e))
finally:
if attached:
win32process.AttachThreadInput(fg, win32api.GetCurrentThreadId(), False)
#else:
#win32gui.SetForegroundWindow(hwnd)
def gotold(hwnd):
if not win32gui.IsWindow(hwnd):
return
_, showCmd, _, _, _ = win32gui.GetWindowPlacement(hwnd)
if showCmd == SW_SHOWMINIMIZED:
win32gui.ShowWindow(hwnd, SW_RESTORE)
else:
win32gui.ShowWindow(hwnd, SW_SHOW)
win32gui.SetForegroundWindow(hwnd)
win32gui.SetActiveWindow(hwnd)
def is_alt_tab_window(hwnd):
"""Check whether a window is shown in alt-tab.
See http://stackoverflow.com/a/7292674/238472 for details.
"""
if not win32gui.IsWindowVisible(hwnd) or not win32gui.IsWindow(hwnd):
return False
hwnd_walk = win32con.NULL
hwnd_try = ctypes.windll.user32.GetAncestor(hwnd, win32con.GA_ROOTOWNER)
while hwnd_try != hwnd_walk:
hwnd_walk = hwnd_try
hwnd_try = ctypes.windll.user32.GetLastActivePopup(hwnd_walk)
if win32gui.IsWindowVisible(hwnd_try):
break
if hwnd_walk != hwnd:
return False
# the following removes some task tray programs and "Program Manager"
ti = TITLEBARINFO()
ti.cbSize = ctypes.sizeof(ti)
ctypes.windll.user32.GetTitleBarInfo(hwnd, ctypes.byref(ti))
if ti.rgstate[0] & win32con.STATE_SYSTEM_INVISIBLE:
return False
# Tool windows should not be displayed either, these do not appear in the
# task bar.
if win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) & win32con.WS_EX_TOOLWINDOW:
return False
pwi = WINDOWINFO()
windll.user32.GetWindowInfo(hwnd, byref(pwi))
# A top-level window created with this style does not become the foreground
# window when the user clicks it. The system does not bring this window to
# the foreground when the user minimizes or closes the foreground window.
# The window does not appear on the taskbar by default.
if pwi.dwExStyle & win32con.WS_EX_NOACTIVATE:
return False
return True
def window_title(hwnd):
return win32gui.GetWindowText(hwnd)
def get_hicon(hWin):
hIcon = win32api.SendMessage(hWin, win32con.WM_GETICON, win32con.FALSE, 0)
if hIcon == win32con.NULL:
hIcon = win32api.SendMessage(hWin, win32con.WM_GETICON, win32con.TRUE, 0)
if hIcon == win32con.NULL:
hIcon = win32gui.GetClassLong(hWin, win32con.GCL_HICONSM)
if hIcon == win32con.NULL:
hIcon = win32gui.GetClassLong(hWin, win32con.GCL_HICON)
if hIcon == win32con.NULL:
hIcon = win32gui.LoadIcon(win32con.NULL, MAKEINTRESOURCE(win32con.IDI_APPLICATION))
return hIcon
def valid_handle(h):
return h != win32con.NULL
def make_qicon(hicon):
width = 16
height = 16
if valid_handle(hicon):
return QPixmap.fromWinHICON(hicon).scaled(width, height)
else:
ret = QPixmap(width, height)
ret.fill(Qt.transparent)
return ret
#def get_file_icon(path):
#i = win32gui.ExtractIconEx(path, 0)[0]
##return win32gui.LoadIcon(i, 0)
#return i
from geticon import get_file_icon
def get_window_icon(hwnd):
"""Return QPixmap."""
#hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICON)
hicon = get_hicon(hwnd)
if not valid_handle(hicon):
return None
try:
return make_qicon(hicon)
except:
return None
#info = win32gui.GetIconInfo(hicon)
#try:
#return QPixmap.fromWinHBITMAP(info[4])
#finally:
#for i in [3, 4]:
#info[i].close()
class tagBITMAPINFOHEADER(Structure):
pass
tagBITMAPINFOHEADER._fields_ = [
('biSize', DWORD),
('biWidth', LONG),
('biHeight', LONG),
('biPlanes', WORD),
('biBitCount', WORD),
('biCompression', DWORD),
('biSizeImage', DWORD),
('biXPelsPerMeter', LONG),
('biYPelsPerMeter', LONG),
('biClrUsed', DWORD),
('biClrImportant', DWORD),
]
PBITMAPINFOHEADER = POINTER(tagBITMAPINFOHEADER)
BITMAPINFOHEADER = tagBITMAPINFOHEADER
LPBITMAPINFOHEADER = POINTER(tagBITMAPINFOHEADER)
class tagRGBQUAD(Structure):
pass
tagRGBQUAD._fields_ = [
('rgbBlue', BYTE),
('rgbGreen', BYTE),
('rgbRed', BYTE),
('rgbReserved', BYTE),
]
RGBQUAD = tagRGBQUAD
LPRGBQUAD = POINTER(RGBQUAD)
class tagBITMAPINFO(Structure):
pass
tagBITMAPINFO._fields_ = [
('bmiHeader', BITMAPINFOHEADER),
('bmiColors', RGBQUAD * 1),
]
PBITMAPINFO = POINTER(tagBITMAPINFO)
LPBITMAPINFO = POINTER(tagBITMAPINFO)
BITMAPINFO = tagBITMAPINFO
def qt_fromWinHBITMAP(hdc, bitmap, w, h):
bmi = BITMAPINFO()
ctypes.memset(ctypes.byref(bmi), 0, ctypes.sizeof(bmi))
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = w
bmi.bmiHeader.biHeight = -h
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 32
bmi.bmiHeader.biCompression = win32con.BI_RGB
bmi.bmiHeader.biSizeImage = w * h * 4
image = QImage(w, h, QImage.Format_ARGB32_Premultiplied)
if image.isNull():
return image
# Get bitmap bits
data = ctypes.create_string_buffer(bmi.bmiHeader.biSizeImage)
if ctypes.windll.gdi32.GetDIBits(
hdc,
bitmap,
0,
h,
data,
ctypes.byref(bmi),
win32con.DIB_RGB_COLORS
):
# Create image and copy data into image.
for y in range(h):
dest = image.scanLine(y);
offset = y * image.bytesPerLine()
dest[:] = data.raw[offset:offset + image.bytesPerLine()]
else:
logging.error("qt_fromWinHBITMAP(), failed to get bitmap bits")
return image
#def fromWinHICON(icon):
#foundAlpha = False
#screenDevice = win32gui.GetDC(0)
#hdc = win32gui.CreateCompatibleDC(screenDevice)
#win32gui.ReleaseDC(0, screenDevice)
#fIcon, xHotspot, yHotspot, hbmMask, hbmColor = win32gui.GetIconInfo(icon) # x and y Hotspot describes the icon center
#w = xHotspot * 2;
#h = yHotspot * 2;
#bitmapInfo = BITMAPINFOHEADER()
#bitmapInfo.biSize = ctypes.sizeof(BITMAPINFOHEADER)
#bitmapInfo.biWidth = w
#bitmapInfo.biHeight = h
#bitmapInfo.biPlanes = 1
#bitmapInfo.biBitCount = 32
#bitmapInfo.biCompression = win32con.BI_RGB
#bitmapInfo.biSizeImage = 0
#bitmapInfo.biXPelsPerMeter = 0
#bitmapInfo.biYPelsPerMeter = 0
#bitmapInfo.biClrUsed = 0
#bitmapInfo.biClrImportant = 0
#winBitmap = ctypes.windll.gdi32.CreateDIBSection(
#hdc,
#ctypes.byref(bitmapInfo),
#win32con.DIB_RGB_COLORS,
#ctypes.c_void_p(),
#win32con.NULL,
#0
#)
#oldhdc = win32gui.SelectObject(hdc, winBitmap)
#win32gui.DrawIconEx(hdc, 0, 0, icon, xHotspot * 2,
#yHotspot * 2, 0, 0, DI_NORMAL)
#image = qt_fromWinHBITMAP(hdc, winBitmap, w, h)
##for y in range(h):
##if foundAlpha:
##break
##QRgb *scanLine= reinterpret_cast<QRgb *>(image.scanLine(y));
##for (int x = 0; x < w ; x++) {
##if (qAlpha(scanLine[x]) != 0) {
##foundAlpha = true;
##break;
##}
##}
##}
##if not foundAlpha):
### If no alpha was found, we use the mask to set alpha values
##win32gui.DrawIconEx(hdc, 0, 0, icon, w, h, 0, 0, win32con.DI_MASK)
##mask = qt_fromWinHBITMAP(hdc, winBitmap, w, h)
##for y in range(h):
##QRgb *scanlineImage = reinterpret_cast<QRgb *>(image.scanLine(y));
##QRgb *scanlineMask = mask.isNull() ? 0 : reinterpret_cast<QRgb *>(mask.scanLine(y));
##for (int x = 0; x < w ; x++){
##if (scanlineMask && qRed(scanlineMask[x]) != 0)
##scanlineImage[x] = 0; //mask out this pixel
##else
##scanlineImage[x] |= 0xff000000; // set the alpha channel to 255
## dispose resources created by iconinfo call
#win32gui.DeleteObject(hbmMask)
#win32gui.DeleteObject(hbmColor)
#win32gui.SelectObject(hdc, oldhdc) # restore state
#win32gui.DeleteObject(winBitmap)
#win32gui.DeleteDC(hdc)
#return QPixmap.fromImage(image)
class tagWINDOWINFO(Structure):
def __str__(self):
return '\n'.join([key + ':' + str(getattr(self, key)) for key, value in self._fields_])
tagWINDOWINFO._fields_ = [
('cbSize', DWORD),
('rcWindow', RECT),
('rcClient', RECT),
('dwStyle', DWORD),
('dwExStyle', DWORD),
('dwWindowStatus', DWORD),
('cxWindowBorders', UINT),
('cyWindowBorders', UINT),
('atomWindowType', ATOM),
('wCreatorVersion', WORD),
]
WINDOWINFO = tagWINDOWINFO
LPWINDOWINFO = POINTER(tagWINDOWINFO)
PWINDOWINFO = POINTER(tagWINDOWINFO)
def top_level_windows():
""" Returns the top level windows in a list of hwnds."""
windows = []
win32gui.EnumWindows(_window_enum_top_level, windows)
return windows
def window_title(hwnd):
return win32gui.GetWindowText(hwnd)
def _window_enum_top_level(hwnd, windows):
""" Window Enum function for getTopLevelWindows """
#if win32gui.GetParent(hwnd) == 0 and title != '':
if is_alt_tab_window(hwnd):
windows.append(hwnd)