def run_elevated(command, args, wait=True):
"""Run the given command as an elevated user and wait for it to return"""
ret = 1
if command.find(' ') > -1:
command = '"' + command + '"'
if platform.system() == 'Windows':
import win32api
import win32con
import win32event
import win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
logging.debug(command + ' ' + args)
process_info = ShellExecuteEx(nShow=win32con.SW_HIDE,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb='runas',
lpFile=command,
lpParameters=args)
if wait:
win32event.WaitForSingleObject(process_info['hProcess'], 600000)
ret = win32process.GetExitCodeProcess(process_info['hProcess'])
win32api.CloseHandle(process_info['hProcess'])
else:
ret = process_info
else:
logging.debug('sudo ' + command + ' ' + args)
ret = subprocess.call('sudo ' + command + ' ' + args, shell=True)
return ret
python类SW_HIDE的实例源码
def sys_tray(self):
import itertools, glob
from sys_tray_icon import SysTrayIcon
# ????
icons = itertools.cycle(glob.glob('*.ico'))
# ???????
hover_text = "QiniuSync"
import ctypes
import win32con
wnd = ctypes.windll.kernel32.GetConsoleWindow()
if wnd != 0:
ctypes.windll.user32.ShowWindow(wnd, win32con.SW_HIDE)
ctypes.windll.kernel32.CloseHandle(wnd)
# ????
def quit_sync():
self.stop_watch()
# ??????
SysTrayIcon(next(icons), hover_text, menu_options=(), on_quit=quit_sync, default_menu_index=1, wnd=wnd)
# ????
def stay_on_bottom(self):
"""Pin to desktop or something close enough (call repeatedly)."""
if self.is_desktop_on_foreground():
if self.topmost is False:
win32gui.SetWindowPos(
self.hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
win32con.SWP_NOSIZE | win32con.SWP_NOMOVE)
self.topmost = True
else:
if self.topmost is True:
win32gui.SetWindowPos(
self.hwnd, win32con.HWND_BOTTOM, 0, 0, 0, 0,
win32con.SWP_NOSIZE | win32con.SWP_NOMOVE)
self.topmost = False
# "To prevent the window button from being placed on the taskbar, create
# the unowned window with the WS_EX_TOOLWINDOW extended style. As an
# alternative, you can create a hidden window and make this hidden window
# the owner of your visible window. The Shell will remove a window's button
# from the taskbar only if the window's style supports visible taskbar
# buttons. If you want to dynamically change a window's style to one that
# doesn't support visible taskbar buttons, you must hide the window first
# (by calling ShowWindow with SW_HIDE), change the window style, and then
# show the window."
# -- https://msdn.microsoft.com/en-us/library/bb776822%28v=vs.85%29.aspx
def ShowDW(self, bShow):
if bShow:
self.toolbar.ShowWindow(win32con.SW_SHOW)
else:
self.toolbar.ShowWindow(win32con.SW_HIDE)
def ShowDW(self, bShow):
if bShow:
self.toolbar.ShowWindow(win32con.SW_SHOW)
else:
self.toolbar.ShowWindow(win32con.SW_HIDE)
def OnInitDialog(self):
self.SetWindowText(self.appName)
butCancel = self.GetDlgItem(win32con.IDCANCEL)
butCancel.ShowWindow(win32con.SW_HIDE)
p1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
p2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
# Do something here!
p1.SetWindowText("Hello there")
p2.SetWindowText("from the demo")
def LoadMainFrame(self):
" Create the main applications frame "
self.frame = self.CreateMainFrame()
self.SetMainFrame(self.frame)
self.frame.LoadFrame(win32ui.IDR_DEBUGGER, win32con.WS_OVERLAPPEDWINDOW)
self.frame.DragAcceptFiles() # we can accept these.
self.frame.ShowWindow(win32con.SW_HIDE);
self.frame.UpdateWindow();
# but we do rehook, hooking the new code objects.
self.HookCommands()
def GUIAboutToFinishInteract(self):
"""Called as the GUI is about to finish any interaction with the user
Returns non zero if we are allowed to stop interacting"""
if self.oldForeground is not None:
try:
win32ui.GetMainFrame().EnableWindow(self.oldFrameEnableState)
self.oldForeground.EnableWindow(1)
except win32ui.error:
# old window may be dead.
pass
# self.oldForeground.SetForegroundWindow() - fails??
if not self.inForcedGUI:
return 1 # Never a problem, and nothing else to do.
# If we are running a forced GUI, we may never get an opportunity
# to interact again. Therefore we perform a "SaveAll", to makesure that
# any documents are saved before leaving.
for template in win32ui.GetApp().GetDocTemplateList():
for doc in template.GetDocumentList():
if not doc.SaveModified():
return 0
# All documents saved - now hide the app and debugger.
if self.get_option(OPT_HIDE):
frame = win32ui.GetMainFrame()
frame.ShowWindow(win32con.SW_HIDE)
return 1
#
# Pythonwin interface - all stuff to do with showing source files,
# changing line states etc.
#
def ShowDW(self, bShow):
if bShow:
self.toolbar.ShowWindow(win32con.SW_SHOW)
else:
self.toolbar.ShowWindow(win32con.SW_HIDE)
def OnInitDialog(self):
self.SetWindowText(self.appName)
butCancel = self.GetDlgItem(win32con.IDCANCEL)
butCancel.ShowWindow(win32con.SW_HIDE)
p1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
p2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
# Do something here!
p1.SetWindowText("Hello there")
p2.SetWindowText("from the demo")
def LoadMainFrame(self):
" Create the main applications frame "
self.frame = self.CreateMainFrame()
self.SetMainFrame(self.frame)
self.frame.LoadFrame(win32ui.IDR_DEBUGGER, win32con.WS_OVERLAPPEDWINDOW)
self.frame.DragAcceptFiles() # we can accept these.
self.frame.ShowWindow(win32con.SW_HIDE);
self.frame.UpdateWindow();
# but we do rehook, hooking the new code objects.
self.HookCommands()
def GUIAboutToFinishInteract(self):
"""Called as the GUI is about to finish any interaction with the user
Returns non zero if we are allowed to stop interacting"""
if self.oldForeground is not None:
try:
win32ui.GetMainFrame().EnableWindow(self.oldFrameEnableState)
self.oldForeground.EnableWindow(1)
except win32ui.error:
# old window may be dead.
pass
# self.oldForeground.SetForegroundWindow() - fails??
if not self.inForcedGUI:
return 1 # Never a problem, and nothing else to do.
# If we are running a forced GUI, we may never get an opportunity
# to interact again. Therefore we perform a "SaveAll", to makesure that
# any documents are saved before leaving.
for template in win32ui.GetApp().GetDocTemplateList():
for doc in template.GetDocumentList():
if not doc.SaveModified():
return 0
# All documents saved - now hide the app and debugger.
if self.get_option(OPT_HIDE):
frame = win32ui.GetMainFrame()
frame.ShowWindow(win32con.SW_HIDE)
return 1
#
# Pythonwin interface - all stuff to do with showing source files,
# changing line states etc.
#
def ShowDW(self, bShow):
if bShow:
self.toolbar.ShowWindow(win32con.SW_SHOW)
else:
self.toolbar.ShowWindow(win32con.SW_HIDE)
def remove_taskbar_button(self):
"""Hide window from taskbar and ALT+TAB dialog."""
win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)
win32api.SetWindowLong(
self.hwnd, win32con.GWL_EXSTYLE,
win32api.GetWindowLong(self.hwnd, win32con.GWL_EXSTYLE)
| win32con.WS_EX_NOACTIVATE
| win32con.WS_EX_TOOLWINDOW)
win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
def hide_extra_ui(self, hwnd=None, remove=True):
"""
:param hwnd: Hwnd to remove all styling from. If not supplied, then the default hwnd is used
:param remove: If true: Removes all styling. If false: Adds back the removed styles
:return: NoneType
"""
logging.debug('Trying to manipulate UI')
if hwnd is None:
hwnd = self.get_hwnd()
style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
if remove:
logging.debug('Removing UI')
style = style | win32con.WS_POPUP
style = style & ~win32con.WS_OVERLAPPEDWINDOW
else:
logging.debug('Adding UI')
style = style & ~win32con.WS_POPUP
style = style | win32con.WS_OVERLAPPEDWINDOW
win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
win32gui.SetWindowLong(hwnd, win32con.GWL_STYLE, style)
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api
import win32con
import win32event
import win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType, types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
#showCmd = win32con.SW_SHOWNORMAL
showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
# print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
#showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
#showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc