def get_hold(self): # 将窗口调到前台,激活 self.__init_handle() # 另起进程处理输入验证码问题 confirm_pro = Process(target=handle_verify, args=(self.__AfxMDIFrame_hwnd, self.__hold_panel_hwnd, self.__data_grid_hwnd)) confirm_pro.start() # ctrl c win32api.keybd_event(win32con.VK_LCONTROL, 0, 0, 0) # 使用 PostMessage 导致客户端退出 # win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', win32con.SMTO_ABORTIFHUNG, 1000 # SMTO_ABORTIFHUNG:如果接收进程处于“hung”状态,不等待超时周期结束就返回。 # SMTO_BLOCK:阻止调用线程处理其他任何请求,直到函数返回。 # SMTO_NORMAL:调用线程等待函数返回时,不被阻止处理其他请求。 # SMTO_NOTIMEOUTIFNOTHUNG:Windows 95及更高版本:如果接收线程没被挂起,当超时周期结束时不返回。 try: win32gui.SendMessageTimeout(self.__data_grid_hwnd, win32con.WM_KEYDOWN, win32api.VkKeyScan('c'), 0, win32con.SMTO_NORMAL, 5) win32gui.SendMessageTimeout(self.__data_grid_hwnd, win32con.WM_KEYUP, win32api.VkKeyScan('c'), 0, win32con.SMTO_NORMAL, 5) except Exception as e: pass win32api.keybd_event(win32con.VK_LCONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) # df = pd.read_clipboard(converters={'证券代码': str}).drop( # columns=['冻结数量', '交易市场', '股东帐户', '汇率', '成本价港币', '成本价港币', '买入成本价港币', '买入在途数量', '卖出在途数量', 'Unnamed: 17', ]) # 返回持仓数量大于 0 的股票 # return df[df["股票余额"] > 0] # todo return pd.read_clipboard() return ''
def send_click(hwnd, x, y, flag=MouseFlag.LeftButton, click_type=MouseClickType.SingleClick): """在目标窗口通过SendMessage方式产生鼠标点击的动作 :param hwnd: 目标窗口句柄 :type hwnd: 整数 :param x: 屏幕x坐标 :type x: 整数 :param y: 屏幕y坐标 :type y: 整数 :param flag: 鼠标键类型 :type flag: 枚举类型, MouseFlag.LeftButton|MouseFlag.MiddleButton|MouseFlag.RightButton :param click_type: 鼠标键点击方式 :type click_type: 枚举类型, MouseClickType.SingleClick | MouseClickType.DoubleClick """ keystate = 0 if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000 != 0: keystate = keystate | win32con.MK_CONTROL if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000 != 0: keystate = keystate | win32con.MK_SHIFT win32api.SetCursorPos((x, y)) time.sleep(0.2) c_x, c_y = win32gui.ScreenToClient(hwnd, (x, y)) if click_type == MouseClickType.SingleClick: try: win32gui.SendMessageTimeout(hwnd, _mouse_msg_param[flag][0], _mouse_msg_param[flag][2] | keystate, (c_y << 16) | c_x, 0, 1000) except win32gui.error as e: if e.winerror == 1400: # 无效窗口句柄,有些窗口post第一个消息后就会消失 pass elif e.winerror == 1460: # timeout win32gui.SendMessageTimeout(hwnd, win32con.WM_NULL, 0, 0, 0, 30000) # 发送NULL确认上个消息已处理 else: raise e try: win32gui.SendMessageTimeout(hwnd, _mouse_msg_param[flag][1], 0 | keystate, (c_y << 16) | c_x, 0, 1000) except win32gui.error as e: if e.winerror == 1400: # 无效窗口句柄,有些窗口post第一个消息后就会消失 pass elif e.winerror == 1460: # timeout win32gui.SendMessageTimeout(hwnd, win32con.WM_NULL, 0, 0, 0, 30000) # 发送NULL确认上个消息已处理 else: raise e else: win32gui.SendMessage(hwnd, _mouse_msg_param[flag][0], _mouse_msg_param[flag][2] | keystate, (c_y << 16) | c_x) win32gui.SendMessage(hwnd, _mouse_msg_param[flag][1], 0 | keystate, (c_y << 16) | c_x) win32gui.SendMessage(hwnd, _mouse_msg_param[flag][3], _mouse_msg_param[flag][2] | keystate, (c_y << 16) | c_x) win32gui.SendMessage(hwnd, _mouse_msg_param[flag][1], 0 | keystate, (c_y << 16) | c_x)
def send_message_timeout(self, message, wparam=0, lparam=0, timeout=None, timeoutflags=win32defines.SMTO_NORMAL): """ Send a message to the control and wait for it to return or to timeout If no timeout is given then a default timeout of .01 of a second will be used. """ if timeout is None: timeout = Timings.sendmessagetimeout_timeout result = -1 try: (_, result) = win32gui.SendMessageTimeout(int(self.handle), message, wparam, lparam, timeoutflags, int(timeout * 1000)) except Exception as exc: #import traceback #print('____________________________________________________________') #print('self.handle =', int(self.handle), ', message =', message, # ', wparam =', wparam, ', lparam =', lparam, ', timeout =', timeout) #print('Exception: ', exc) #print(traceback.format_exc()) result = str(exc) return result #result.value
def broadcast_change(): """ Refresh the windows environment. .. note:: This will only effect new processes and windows. Services will not see the change until the system restarts. Returns: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.broadcast_change() """ # https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx _, res = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0, win32con.SMTO_ABORTIFHUNG, 5000, ) return not bool(res)
def rehash(): ''' Send a WM_SETTINGCHANGE Broadcast to Windows to rehash the Environment variables ''' return win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', 0, 10000)[0] == 1
def initUI(self): viewId = self.winId() workerW = self._findWindowHandles(windowClass='Progman')[0] crypticParams = (0x52c, 0, 0, win32con.SMTO_NORMAL, 0x3e8) win32gui.SendMessageTimeout(workerW, *crypticParams) win32gui.EnumWindows(EnumWindowsProc(), None) win32gui.ShowWindow(_WORKERW, win32con.SW_SHOW) #win32gui.GetWindowLong(viewId, win32con.GWL_STYLE) #win32gui.SetWindowPos(viewId, win32con.HWND_TOP, 0,0,0,0, \ # win32con.WS_EX_LEFT|win32con.WS_EX_LTRREADING|win32con.WS_EX_RIGHTSCROLLBAR|win32con.SWP_NOACTIVATE) self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.CoverWindow | Qt.WindowStaysOnBottomHint) self.setWindowState(Qt.WindowNoState) self.setFocusPolicy(Qt.NoFocus) win32gui.SetParent(viewId, workerW) self.load( QUrl( 'C:/Users/Daniil (WORK)/Desktop/Wallpaper3/html/example/index.html' )) self.showFullScreen() self.show()
def TestObjectFromWindow(): # Check we can use ObjectFromLresult to get the COM object from the # HWND - see KB Q249232 # Locating the HWND is different than the KB says... hwnd = win32gui.FindWindow('IEFrame', None) for child_class in [ 'TabWindowClass', 'Shell DocObject View', 'Internet Explorer_Server' ]: hwnd = win32gui.FindWindowEx(hwnd, 0, child_class, None) # ack - not working for markh on vista with IE8 (or maybe it is the # lack of the 'accessibility' components mentioned in Q249232) # either way - not working! return # But here is the point - once you have an 'Internet Explorer_Server', # you can send a message and use ObjectFromLresult to get it back. msg = win32gui.RegisterWindowMessage("WM_HTML_GETOBJECT") rc, result = win32gui.SendMessageTimeout(hwnd, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000) ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0) doc = Dispatch(ob) # just to prove it works, set the background color of the document. for color in "red green blue orange white".split(): doc.bgColor = color time.sleep(0.2)
def set_environment(**kwargs): root = registry.registry("HKCU") env = root.Environment for label, value in kwargs.iteritems(): env.set_value(label, value) win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 2000)
def _GetWorkerW(): progman = win32gui.FindWindow("Progman", None) win32gui.SendMessageTimeout(progman, 0x052C, 0, 0, win32con.SMTO_NORMAL, 0x3E8) win32gui.EnumWindows(_EnumWindowsProc, None) win32gui.ShowWindow(_workerw, win32con.SW_HIDE) return progman
def addbindir2path(): if sys.platform != 'win32' or not winextensions: return # Add py/bin to PATH environment variable bindir = os.path.join(sysconfig.get_python_lib(), "py", "bin", "win32") # check for the user path ureg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) ukey = r"Environment" # not every user has his own path on windows try: upath = get_registry_value(ureg, ukey, "PATH") except WindowsError: upath="" # if bindir allready in userpath -> do nothing if bindir in upath: return reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment" path = get_registry_value(reg, key, "Path") # if bindir allready in systempath -> do nothing if bindir in path: return path += ";" + bindir print "Setting PATH to:", path pathset=False try: set_registry_value(reg, key, "PATH", path) pathset=True except WindowsError: print "cannot set systempath, falling back to userpath" pass if not pathset: try: if len(upath)>0: #if no user path present upath += ";" upath+=bindir set_registry_value(ureg, ukey, "Path", upath) pathset=True except WindowsError: print "cannot set userpath, please add %s to your path" % (bindir,) return #print "Current PATH is:", get_registry_value(reg, key, "Path") # Propagate changes throughout the system win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000) # Propagate changes to current command prompt p = subprocess.Popen("set PATH=%s" % path, shell=True) os.waitpid(p.pid, 0)
def broadcast(timeout_ms=2000): ur"""Broadcast a message to all top-level windows informing them that an environment change has occurred. The message must be sent, not posted, and times out after `timeout_ms` ms since some top-level windows handle this badly. NB This is a static method. """ win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, timeout_ms)
def spark_set_env_vars(spark_version_dir): import glob zipfiles = glob.glob( os.path.join(spark_version_dir, "python", "lib", "*.zip")) if zipfiles != [] and zipfiles[0] not in sys.path: position = [ index for (index, path) in enumerate(sys.path) if re.match(SPARK_VERSIONS_FILE_PATTERN, path) ] or len(sys.path) sys.path = sys.path[:position] + zipfiles + sys.path[position:] persistent_vars = {} path_delim = ";" if sys.platform == "win32" else ":" path_values = os.environ.get("PYTHONPATH", "").split(path_delim) if zipfiles != [] and zipfiles[0] not in path_values: position = [ index for (index, path) in enumerate(path_values) if re.match(SPARK_VERSIONS_FILE_PATTERN, path) ] or len(path_values) path_values = path_values[:position] + zipfiles + path_values[position:] os.environ["PYTHONPATH"] = path_delim.join(path_values) persistent_vars["PYTHONPATH"] = path_delim.join(path_values) if os.environ.get("SPARK_HOME", "") != spark_version_dir: os.environ["SPARK_HOME"] = spark_version_dir persistent_vars["SPARK_HOME"] = spark_version_dir if persistent_vars == {}: return if sys.platform == "win32": try: import _winreg as winreg except ImportError: import winreg logger.info( "Setting the following variables in your registry under HKEY_CURRENT_USER\\Environment:" ) for k, v in persistent_vars.items(): logger.info("%s = %s (REG_SZ)" % (k, v)) with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) as hkey: for value, value_data in persistent_vars.items(): winreg.SetValueEx(hkey, value, 0, winreg.REG_SZ, value_data) import win32gui, win32con win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000) else: logger.info( "Set the following environment variables in your ~/.bashrc: ") for k, v in persistent_vars.iteritems(): logger.info("export %s = %s" % (k, v))
def close_window_by_hwnd(hwnd: int): """Close window by window handle (HWND) :param hwnd: HWND in decimal """ if window_exist_by_hwnd(hwnd): try: set_focus_on_window(hwnd) except Exception: logger.debug('Could not set focus on window. continue...') try: flags = win32con.SMTO_BLOCK + win32con.SMTO_ABORTIFHUNG + win32con.SMTO_NOTIMEOUTIFNOTHUNG win32gui.SendMessageTimeout(hwnd, 0x10, 0, 0, flags, 1000) win32gui.SendMessageTimeout(hwnd, 0x10, 0, 0, flags, 1000) except Exception as e: logger.debug('Got error while trying to close the window, details:{error}'.format(error=e)) return True else: logger.debug('Could not find the HWND: {}'.format(hwnd)) return False
def connect(self): """ Connect to skype. """ win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, self.api_discover, self._win, win32con.SMTO_NORMAL, 0, 5*1000 )
def SendSettingChange(self): """ This updates all windows with registry changes to the HKCU\Environment key. """ import win32gui, win32con ret = win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_NORMAL, 1000) return ret
def pywin32_update_system(): """ use pywin32 to call SendMessageTimeout to send broadcast to all windows. """ import win32gui import win32con rc, dwReturnValue = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000)
def sub_menu(self): """Return the SubMenu or None if no submenu""" submenu_handle = self._read_item().hSubMenu if submenu_handle: win32gui.SendMessageTimeout(self.ctrl.handle, win32defines.WM_INITMENUPOPUP, submenu_handle, self._index, win32defines.SMTO_NORMAL, 0) return Menu(self.ctrl, submenu_handle, False, self) return None
def rehash(): ''' Send a WM_SETTINGCHANGE Broadcast to Windows to refresh the Environment variables CLI Example: ... code-block:: bash salt '*' win_path.rehash ''' return win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', 0, 10000)[0] == 1
def close_browser_by_hwnd(hwnd: int, handle_multiple_ie_tabs=True) -> bool: """Close browser window by hwnd :param hwnd: Hwnd of the browser window :param handle_multiple_ie_tabs: Will attempt to press the close all tabs in IE :return: True if the browser window closed successfully """ if not hwnd: logger.debug('No active hwnd was given, returns True') return True try: thread_id, pid = win32process.GetWindowThreadProcessId(hwnd) shell = win32com.client.Dispatch("WScript.Shell") if not window_focus_by_hwnd(hwnd): return True shell.SendKeys("%", 0) time.sleep(1) window_title = get_window_text(hwnd) if not window_title: return True logger.debug( "Closing hwnd: {hw}, with title: {title}, time: {t}".format( hw=hwnd, title=window_title, t=datetime.now())) # win32gui.SendMessage(hwnd, 0x10, 0, 0) flags = win32con.SMTO_BLOCK + win32con.SMTO_NOTIMEOUTIFNOTHUNG win32gui.SendMessageTimeout(hwnd, 0x10, 0, 0, flags, 1000) time.sleep(2) if handle_multiple_ie_tabs: logger.debug('Checking for "close all tabs" popup') ie_close_all_tabs_window_hwnds = get_hwnds_by_class("#32770") for msg_hwnd in ie_close_all_tabs_window_hwnds: btn_hwnd = win32gui.FindWindowEx(msg_hwnd, 0, "Button", "Close all &tabs") if btn_hwnd > 0: win32api.PostMessage(btn_hwnd, win32con.WM_LBUTTONDOWN, 0, 0) time.sleep(0.3) win32api.PostMessage(btn_hwnd, win32con.WM_LBUTTONUP, 0, 0) end_time = time.time() + 20 while psutil.pid_exists(pid) and time.time() < end_time: time.sleep(2) if time.time() > end_time: logger.error( 'Failed to close window {title} with pid {pid}'.format( title=window_title, pid=pid)) return False return True except Exception as ex: logger.error( f'Got an error when trying to close a window with error: {ex}') return False
def __init__(self, WindowsName=None, IntPtr=None): self.worker = "" self.hwndChild = "" self.WindowsName = WindowsName progman = win32gui.FindWindow("Progman", None) win32gui.SendMessageTimeout(progman, 0x052C, 0, 0, win32con.SMTO_NORMAL, 1000) win32gui.EnumWindows(self.GetHandleWorkerW, None) if IntPtr != None: win32gui.SetParent(IntPtr, self.worker) else: win32gui.EnumWindows(self.GetHandleWallpaperWindows, None) # print(self.hwndChild) win32gui.SetParent(self.hwndChild, self.worker)
def main(): time.sleep(3) ffplay = win32gui.FindWindow(None, "pynamic_player") progman = win32gui.FindWindow("Progman", "Program Manager") win32gui.SendMessageTimeout(progman, 0x052C, 0, 0, win32con.SMTO_NORMAL, 1000) time.sleep(0.1) hwnd = win32gui.GetWindow(progman, win32con.GW_HWNDPREV) wkwname = win32gui.GetClassName(hwnd) print(wkwname) if wkwname == "WorkerW": win32gui.SetParent(ffplay, hwnd) win32gui.SetWindowPos(ffplay, win32con.HWND_BOTTOM, 0, 0, w, h, 0 | win32con.SWP_NOZORDER)
def broadcast_change(): ''' Refresh the windows environment. Returns (bool): True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' reg.broadcast_change ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx _, res = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0, win32con.SMTO_ABORTIFHUNG, 5000) return not bool(res)
def monoff(): #Since sleep has an upper limit (as it was spitting errors at me for excessively high values), I decided to do t in minutes with while. i = 0 #Simple incremental loop. while i < t: time.sleep(60) i = i + 1 cd = t - i print(' ', cd, 'minute(s) remaining.') #Variable for setting state of the display SC_MONITORPOWER = 0xF170 ''' Sends message, with a timeout option of 15 seconds (probably overkill), to broadcast to all windows that the display is to be set to '2' (which is off) If timeout is reached, app is considered hung and exits. More info here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644952%28v=vs.85%29.aspx ''' win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, SC_MONITORPOWER, 2, 0x0002, 15000)
def set_behind_icons(self): self.set_size(1920, 1080) progman = win32gui.FindWindow("Progman", None) result = win32gui.SendMessageTimeout(progman, 0x052c, 0, 0, 0x0, 1000) workerw = 0 def _enum_windows(tophandle, topparamhandle): p = win32gui.FindWindowEx(tophandle, 0, "SHELLDLL_DefView", None) if p != 0: workerw = win32gui.FindWindowEx(0, tophandle, "WorkerW", None) pyglet_hwnd = self._hwnd pyglet_hdc = win32gui.GetWindowDC(pyglet_hwnd) # win32gui.SetParent(pyglet_hwnd, workerw) return True win32gui.EnumWindows(_enum_windows, 0) # sets window behind icons self.set_location(0, 0)
def sendMessage(hwnd, retMsg, timeoutSec): char_buffer = array.array("c", retMsg) int_data = 0 char_buffer_address = char_buffer.buffer_info()[0] char_buffer_size = char_buffer.buffer_info()[1] copy_struct = struct.pack(g_CopyFmt, int_data, char_buffer_size, char_buffer_address) retA = 0 retB = 0 retA, retB = win32gui.SendMessageTimeout(hwnd, win32con.WM_COPYDATA, 0, copy_struct, win32con.SMTO_NORMAL, timeoutSec * 1000) # milisec return retA, retB
def GetWorkerWhdwnd(): # Get the handle of program manager hProgMan = win32gui.FindWindow("Progman", None) # print("hProgMan:",hProgMan) # Send a message to program manager to split 'FolderView' and 'SysListView' into WorkerW, # 参数为0时,无法工作 rc,result = win32gui.SendMessageTimeout(hProgMan, 0x052C, 0x0000000D, 1, win32con.SMTO_NORMAL, 1000) # rc,result = win32gui.SendMessageTimeout(hProgMan, 0x052C, 0x0000000D, 0, win32con.SMTO_NORMAL, 1000) # print('rc,result:',rc,result) # print("win32 error:",win32api.GetLastError()) arhWorkerW = [] def GetWorkerWs(hwnd,mouse): if win32gui.GetClassName(hwnd) == 'WorkerW' : arhWorkerW.append(hwnd) #print('hwnd:',hex(hwnd),"wdnm:%15s"%win32gui.GetWindowText(hwnd), # 'class:%15s'%win32gui.GetClassName(hwnd)) win32gui.EnumWindows(GetWorkerWs, 0) return arhWorkerW[-1]
def safe_get_window_text(hwnd): """ Safely get the window text (title) of a specified window :param hwnd: window handle to get the text of :returns: window title if found """ title = "" try: # Note - we use SendMessageTimeout instead of GetWindowText as the later # will hang if the target window isn't processing messages for some reason buffer_sz = 1024 buffer = win32gui.PyMakeBuffer(buffer_sz) _, result = win32gui.SendMessageTimeout( hwnd, win32con.WM_GETTEXT, buffer_sz, buffer, win32con.SMTO_ABORTIFHUNG | win32con.SMTO_BLOCK, 100) if result != 0: title = buffer[:result] except: pass return title
def SetEnvironmentVariable(variableName, variableValue): import winreg, win32gui, win32con try: path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) key = winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, variableName, 0, winreg.REG_EXPAND_SZ, variableValue) winreg.CloseKey(key) winreg.CloseKey(reg) win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, u'Environment', win32con.SMTO_ABORTIFHUNG, 500) except Exception as e: print(e)
def main(): #################### # Registry #################### root_key = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER) sub_key = _winreg.CreateKey(root_key,"Environment") print "" print "Clearing environment variables from the current user's registry:" print "" clear_variable(sub_key, "ROS_ROOT") clear_variable(sub_key, "ROS_MASTER_URI") clear_variable(sub_key, "ROS_HOME") clear_variable(sub_key, "ROS_IP") clear_variable(sub_key, "ROS_PACKAGE_PATH") clear_variable(sub_key, "PATH") clear_variable(sub_key, "PYTHONHOME") clear_variable(sub_key, "PYTHONPATH") #################### # Broadcasting #################### try: import win32gui import win32con win32gui.SendMessageTimeout(win32con.HWND_BROADCAST,win32con.WM_SETTINGCHANGE, 0,"Environment", 0, 1000 ) except: print "Note that registry env variable changes aren't picked up by programs unless you log off, log on" print " OR" print "you have installed pywin32 so that this script can broadcast the change." print "" print "To install pywin32, download the appropraite file from:" print " http://sourceforge.net/projects/pywin32/files/pywin32/" print "" os.system("pause") return 0
def run(self): global SHUTDOWN global BUS_SHUTDOWN global g_TEST_FLAG global g_BUS_QUEUE # deque t1_time = time.time() nCnt = 0 while 1: try: notiData = g_BUS_QUEUE.pop() if (len(notiData) == 2): # cmd, msg #{ cmd = notiData[0] msg = notiData[1] if msg != '': __LOG__.Trace( "%-10s| QUEUE DATA, len:[%d]" % ("DEBUG", len(msg)), logging.DEBUG) self.checkKey(cmd, msg) #} ##time.sleep(0.001) if g_TEST_FLAG: if nCnt == 0: t1_time = time.time() nCnt = nCnt + 1 if BUS_SHUTDOWN: # -- TESTSUITE calcPerf(t1_time, nCnt, "QUEUE") except IndexError: if BUS_SHUTDOWN: # -- TESTSUITE calcPerf(t1_time, nCnt, "QUEUE") if SHUTDOWN: if (len(g_BUS_QUEUE) > 0): __LOG__.Trace( "%-10s| SHUTDOWN , remain QUEUE :[%d]" % ("ERROR", len(g_BUS_QUEUE)), logging.ERROR) continue else: __LOG__.Trace( "%-10s| SHUTDOWN , no Data QUEUE :[%d]" % ("ERROR", len(g_BUS_QUEUE)), logging.ERROR) break time.sleep(0.001) continue # no data __LOG__.Trace("QUEUE Thread end before") try: if g_HWNDMAIN: ##win32gui.SendMessage( g_HWNDMAIN, win32con.WM_DESTROY, 0, 0 ) win32gui.SendMessageTimeout(g_HWNDMAIN, win32con.WM_DESTROY, 0, 0, win32con.SMTO_NORMAL, 1000) # milisec, 1 sec except: __LOG__.Exception() __LOG__.Trace("+++ QUEUE Thread End OK!!!")