美文网首页
Python 获取Windows关机消息

Python 获取Windows关机消息

作者: Bug2Coder | 来源:发表于2019-04-22 16:22 被阅读0次
Windows 在注销、重起、关机之前会向每个当前正在运行的应用程序发送WM_QUERYENDSESSION消息
def log_info(msg):
    """ Prints """
    print(msg)
    f = open("c:\\test.log", "a")
    f.write(msg + "\n")
    f.close()


def wndproc(hwnd, msg, wparam, lparam):
  """
  关机等捕获到消息后执行的程序
  """
    log_info("wndproc: %s" % msg)


if __name__ == "__main__":
    log_info("*** STARTING ***")
    hinst = win32api.GetModuleHandle(None)
    wndclass = win32gui.WNDCLASS()
    wndclass.hInstance = hinst
    wndclass.lpszClassName = "testWindowClass"
    messageMap = {
                  win32con.WM_QUERYENDSESSION: wndproc,    
                  win32con.WM_ENDSESSION: wndproc,
                  }

    wndclass.lpfnWndProc = messageMap

    try:
        myWindowClass = win32gui.RegisterClass(wndclass)    # 注册窗口类
        hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,      # 实例化对象
                                       myWindowClass,
                                       "Testwindows",
                                       0,
                                       0,
                                       0,
                                       win32con.CW_USEDEFAULT,
                                       win32con.CW_USEDEFAULT,
                                       0,
                                       0,
                                       hinst,
                                       None)
    except Exception as e:
        log_info("Exception: %s" % str(e))

    if hwnd is None:
        log_info("hwnd is none!")
    else:
        log_info("hwnd: %s" % hwnd)

    while True:
        win32gui.PumpWaitingMessages()
        time.sleep(1)

相关文章

网友评论

      本文标题:Python 获取Windows关机消息

      本文链接:https://www.haomeiwen.com/subject/frqugqtx.html