def set_monitors():
    global hwnd
    surface = pygame.display.set_mode((800, 480), NOFRAME, 32)  # window's create
    monitors = win32api.EnumDisplayMonitors()  # list of monitors' coords information/

    hwnd = win32gui.GetForegroundWindow()  # get id of the top window(hwnd is integer)

    win32gui.ShowWindow(hwnd, win32con.SHOW_FULLSCREEN)  # fullscreen

    win32gui.MoveWindow(hwnd, win32api.GetMonitorInfo(monitors[1][0])['Monitor'][0],  # move this window
                        win32api.GetMonitorInfo(monitors[1][0])['Monitor'][1],
                        800,
                        480, 0)
    return surface
Exemple #2
0
def init():
    """
    Executed once before the main loop,
    Finds the game window, and calculates the offset to remove the title bar
    """
    # noinspection PyUnresolvedReferences
    try:
        WindowServer.hwnd = win32gui.FindWindow(None, "Elder Scrolls Online")

        monitor_id = windll.user32.MonitorFromWindow(WindowServer.hwnd, 2)
        WindowServer.monitor_top_left = win32api.GetMonitorInfo(
            monitor_id)["Monitor"][:2]

        rect = win32gui.GetWindowRect(WindowServer.hwnd)
        client_rect = win32gui.GetClientRect(WindowServer.hwnd)
        WindowServer.windowOffset = math.floor(
            ((rect[2] - rect[0]) - client_rect[2]) / 2)
        WindowServer.status = Status.RUNNING

        WindowServer.d3.display = next(
            (m for m in WindowServer.d3.displays if m.hmonitor == monitor_id),
            None)

    except pywintypes.error:
        logging.error("Game window not found")
        WindowServer.status = Status.CRASHED
Exemple #3
0
def script_update(settings):	
	global g
	g.settings = settings

	global slide_scene
	slide_scene = obs.obs_data_get_string(settings, "slide_scene")

	global monitors
	monitors = []
	for hMonitor, hdcMonitor, pyRect in win32api.EnumDisplayMonitors():
		monitors.append(Monitor(hMonitor, hdcMonitor, pyRect, win32api.GetMonitorInfo(hMonitor)["Device"])) 

	global monitor
	monitor = obs.obs_data_get_int(settings, "monitor")

	global screen_sourcename
	screen_sourcename = obs.obs_data_get_string(settings, "screen_sourcename")

	global slide_visible_duration
	slide_visible_duration = obs.obs_data_get_int(settings, "slide_visible_duration")

	global fadeout_duration
	fadeout_duration = obs.obs_data_get_double(settings, "fadeout_duration")

	global refresh_interval
	refresh_interval = obs.obs_data_get_double(settings, "refresh_interval")

	global camera_sourcename
	camera_sourcename = obs.obs_data_get_string(settings, "camera_sourcename")
Exemple #4
0
    def __init__(self):
        print "initializing frame grabber"
        self._grabber = FrameGrabber()
        print "frame grabber initialized"

        print "learning skin color"
        self._learnHist()
        print "skin color learned"
        self._winname = "GRS"
        self._dilationFilter = cv2.getStructuringElement(
            cv2.MORPH_ELLIPSE, (9, 4))

        #intialize detector
        self._detector = BProjectionDetector(self._hist)

        self._selection = (120, 120, 80, 80)
        #initialize tracker
        self._tracker = CamShiftTracker(
            (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 10, 1))

        #initialize recognizer
        self._recognizer = HandRecognizer()

        self._handler = MouseHandler()

        self._fstartx = 100
        self._fstarty = 80

        dict = wa.GetMonitorInfo(1)  #argument 1 for standard input Monitor
        _, _, xmax, ymax = dict['Monitor']

        #self._fwidth = int(0.4 * xmax)
        self._fwidth = 440
        self._fheight = 320
Exemple #5
0
    def from_monitor_handle(cls, handle):
        """Create a monitor from a handle for a monitor

        Parameters
        ---------
        handle : int
            Monitor handle from EnumDisplayMonitors

        Notes
        -----
        See https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmonitorinfoa
        and
        https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumdisplaydevicesa
        for more information.
        """
        # https://docs.microsoft.com/en-us/windows/win32/api/windef/ns-windef-rect
        info = win32api.GetMonitorInfo(handle)
        device = win32api.EnumDisplayDevices(info["Device"], 0)
        area_left, area_top, area_right, area_bottom = info["Monitor"]
        work_left, work_top, work_right, work_bottom = info["Work"]
        return cls(
            area=Rectangle(area_left, area_right, area_top, area_bottom),
            work=Rectangle(work_left, work_right, work_top, work_bottom),
            is_primary=info["Flags"] == 1,
            name=info["Device"].lstrip("\\\\.\\"),
            id=device.DeviceID,
        )
Exemple #6
0
def get_window_taskbar_size():
    resW, resH = get_screen_resolution()
    monitors = win32api.EnumDisplayMonitors()
    display1 = win32api.GetMonitorInfo(monitors[0][0])
    tbH = resH - display1['Work'][3]
    tbW = resW
    return tbW, tbH
Exemple #7
0
def get_workareas():
    try:
        workareas = []
        for m in win32api.EnumDisplayMonitors(None, None):
            mi = win32api.GetMonitorInfo(m[0])
            screenlog("get_workareas() GetMonitorInfo(%s)=%s", m[0], mi)
            #absolute workarea / monitor coordinates:
            wx1, wy1, wx2, wy2 = mi['Work']
            mx1, my1, mx2, my2 = mi['Monitor']
            assert mx1 < mx2 and my1 < my2, "invalid monitor coordinates"
            #clamp to monitor, and make it all relative to monitor:
            rx1 = max(0, min(mx2 - mx1, wx1 - mx1))
            ry1 = max(0, min(my2 - my1, wy1 - my1))
            rx2 = max(0, min(mx2 - mx1, wx2 - mx1))
            ry2 = max(0, min(my2 - my1, wy2 - my1))
            assert rx1 < rx2 and ry1 < ry2, "invalid relative workarea coordinates"
            geom = rx1, ry1, rx2 - rx1, ry2 - ry1
            #GTK will return the PRIMARY monitor first,
            #so we have to do the same thing:
            if mi['Flags'] & MONITORINFOF_PRIMARY:
                workareas.insert(0, geom)
            else:
                workareas.append(geom)
        assert len(workareas) > 0
        screenlog("get_workareas()=%s", workareas)
        return workareas
    except Exception as e:
        screenlog.warn("failed to query workareas: %s", e)
        return []
Exemple #8
0
def initMonitors():
    global Monitors

    for mhnd in win32api.EnumDisplayMonitors(None, None):
        info = win32api.GetMonitorInfo(mhnd[0])

        monitor = Monitor(info)
        DesktopArea.extend_to_cover(monitor.rect)
        Monitors.append(monitor)

    # Sort monitors by position so their order stays the same
    Monitors.sort(
        key=lambda x: math.floor(x.rect.top / 900.0) * -10000 + x.rect.left)

    # Rotate monitors so the default monitor is at index 0
    for i, monitor in enumerate(Monitors):
        if monitor.primary:
            Monitors = Monitors[i:] + Monitors[:i]
            break

    # Make sure each monitor knows the correct index
    for i, monitor in enumerate(Monitors):
        monitor.monitor_index = i

    for i, monitor in enumerate(Monitors):
        print(f"Monitor {i}: {monitor.rect}")
    def MonitorEnumProc_callback(hMonitor, hdcMonitor, lprcMonitor, dwData):
        class MONITORINFOEX(ctypes.Structure):
            _fields_ = [("cbSize", ctypes.wintypes.DWORD),
                        ("rcMonitor", ctypes.wintypes.RECT),
                        ("rcWork", ctypes.wintypes.RECT),
                        ("dwFlags", ctypes.wintypes.DWORD),
                        ("szDevice", ctypes.wintypes.WCHAR * CCHDEVICENAME)]

        lpmi = MONITORINFOEX()
        lpmi.cbSize = ctypes.sizeof(MONITORINFOEX)
        #win32api.GetMonitorInfo(hMonitor, ctypes.byref(lpmi))
        monitor_info = win32api.GetMonitorInfo(hMonitor)
        #hdc = self._gdi32.CreateDCA(ctypes.c_char_p(lpmi.szDevice), 0, 0, 0)
        #print('================== szDevice {}'.format(lpmi.szDevice))
        print('================== szDevice {}'.format(monitor_info))
        monitor = win32api.EnumDisplayDevices(monitor_info['Device'], 0)
        print('monitor DeviceID {}; handle {}; rect {}'.format(
            monitor.DeviceID, hMonitor, monitor_info['Monitor']))

        # lprcMonitor.contents matches monitor_info['Monitor']
        rct = lprcMonitor.contents
        print('        lprcMonitor (l t r b ) {} {} {} {}'.format(
            rct.left, rct.top, rct.right, rct.bottom))

        monitors.append(
            MonitorData(hMonitor, monitor.DeviceID, monitor_info['Monitor']))

        return True
def get_active_monitor():
    #for hMonitor, hdcMonitor, rect in win32api.EnumDisplayMonitors(None, None):
    #    print rect, win32api.GetMonitorInfo(hMonitor)
    #    #print win32api.GetMonitorInfo(hMonitor)
    return win32api.GetMonitorInfo(
        win32api.MonitorFromPoint(get_cursor_pos(),
                                  win32con.MONITOR_DEFAULTTONEAREST))
def init_window(hwnd, min_speed, max_speed):
    monitor_info = win32api.GetMonitorInfo(win32api.MonitorFromWindow(hwnd))
    speed_x = get_randomized_speed(min_speed, max_speed)
    speed_y = get_randomized_speed(min_speed, max_speed)
    window = Wndw(hwnd, (speed_x, speed_y), win32gui.GetWindowRect(hwnd),
                  monitor_info["Work"])
    return window
Exemple #12
0
def detect_current_display() -> int:
    win_id = windll.user32.GetForegroundWindow()
    monitor_default_to_nearest = 2
    active_monitor_id = windll.user32.MonitorFromWindow(
        win_id, monitor_default_to_nearest)
    logging.debug(f'active_monitor_id={active_monitor_id}')

    monitors = win32api.EnumDisplayMonitors()
    logging.debug(f'monitors={monitors}')
    for i, monitor in enumerate(monitors):
        logging.debug(win32api.GetMonitorInfo(monitor[0].handle))
        display_id = int(
            win32api.GetMonitorInfo(
                monitor[0].handle)['Device'].split('DISPLAY')[-1])
        if monitor[0].handle == active_monitor_id:
            logging.debug(f'display_id={display_id}')
            return display_id
Exemple #13
0
def get_target_monitors(target_monitors):
    monitor_handles = win32api.EnumDisplayMonitors()
    targets = []
    for monitor in monitor_handles:
        monitor_info = win32api.GetMonitorInfo(monitor[0])
        if monitor_info.get('Device') in target_monitors:
            targets.append(monitor)
    return targets
Exemple #14
0
 def set_main_mon_idx(self):
     mons = win32api.EnumDisplayMonitors()
     mon_infos = [win32api.GetMonitorInfo(mon[0]) for mon in mons]
     mon_infos.sort(key=lambda info: info['Work'][0])
     primary_monitors = [mi for mi in mon_infos if mi['Flags'] == 1]
     n_primary_monitors = len(primary_monitors)
     if n_primary_monitors != 1:
         print(f'Found {n_primary_monitors} primary monitors. Expected 1.')
     self.mon_idx_def = mon_infos.index(primary_monitors[0])
Exemple #15
0
    def name(self):
        """
        The device name of this monitor.

        :rtype: str
        :returns: monitor name
        """
        monitor_info = win32api.GetMonitorInfo(self._handle)
        return monitor_info["Device"]
Exemple #16
0
    def is_primary(self):
        """
        Whether this is the primary display monitor.

        :rtype: bool
        :returns: true or false
        """
        monitor_info = win32api.GetMonitorInfo(self._handle)
        return monitor_info["Flags"] & 1 == 1
Exemple #17
0
def 副显示器区域(margin=6):
    monitors = win32api.EnumDisplayMonitors()
    区域 = win32api.GetMonitorInfo(monitors[1][0])['Work']
    a, b, c, d = 区域
    x = a
    y = b
    w = c - a
    d = d - b
    return x-margin, y, w+2*margin, d+margin
Exemple #18
0
    def resize(self, width=250, height=450):
        monitor_info = win32api.GetMonitorInfo(
            win32api.MonitorFromPoint((0, 0)))
        work_area = monitor_info["Work"]

        self.root.minsize(width, height)
        self.root.geometry('%dx%d+%d+%d' % (width, height,
                                            (work_area[2] / 2) - (width / 2),
                                            (work_area[3] / 2) - (height / 2)))
Exemple #19
0
def 主显示器右下(margin=7): 
    monitors = win32api.EnumDisplayMonitors()
    区域 = win32api.GetMonitorInfo(monitors[0][0])['Work']
    a, b, c, d = 区域
    x = a
    y = b
    w = c - a
    d = d - b
    return x+w//2, y+d//2, w//2, d//2+margin
Exemple #20
0
def get_workarea():
    #this is for x11 servers which can only use a single workarea,
    #calculate the total area:
    try:
        #first we need to find the absolute top-left and bottom-right corners
        #so we can make everything relative to 0,0
        monitors = []
        for m in win32api.EnumDisplayMonitors(None, None):
            mi = win32api.GetMonitorInfo(m[0])
            mx1, my1, mx2, my2 = mi['Monitor']
            monitors.append((mx1, my1, mx2, my2))
        minmx = min(x[0] for x in monitors)
        minmy = min(x[1] for x in monitors)
        maxmx = max(x[2] for x in monitors)
        maxmy = max(x[3] for x in monitors)
        screenlog("get_workarea() absolute total monitor area: %s",
                  (minmx, minmy, maxmx, maxmy))
        screenlog(" total monitor dimensions: %s",
                  (maxmx - minmx, maxmy - minmy))
        workareas = []
        for m in win32api.EnumDisplayMonitors(None, None):
            mi = win32api.GetMonitorInfo(m[0])
            #absolute workarea / monitor coordinates:
            wx1, wy1, wx2, wy2 = mi['Work']
            workareas.append((wx1, wy1, wx2, wy2))
        assert len(workareas) > 0
        minwx = min(w[0] for w in workareas)
        minwy = min(w[1] for w in workareas)
        maxwx = max(w[2] for w in workareas)
        maxwy = max(w[3] for w in workareas)
        #sanity checks:
        assert minwx >= minmx and minwy >= minmy and maxwx <= maxmx and maxwy <= maxmy, "workspace %s is outside monitor space %s" % (
            (minwx, minwy, maxwx, maxwy), (minmx, minmy, maxmx, maxmy))
        #now make it relative to the monitor space:
        wx1 = minwx - minmx
        wy1 = minwy - minmy
        wx2 = maxwx - minmx
        wy2 = maxwy - minmy
        assert wx1 < wx2 and wy1 < wy2, "invalid workarea coordinates: %s" % (
            wx1, wy1, wx2, wy2)
        return wx1, wy1, wx2 - wx1, wy2 - wy1
    except Exception as e:
        screenlog.warn("failed to query workareas: %s", e)
        return []
Exemple #21
0
    def get_display_info(*args):
        '''
        Returns a dictionary of info about all detected monitors or a selection of monitors

        Args:
            args (tuple): [*Optional*] a variable list of monitors. Pass in a monitor's name/serial/model/index and only the information corresponding to these monitors will be returned

        Returns:
            list: list of dicts if `args` is empty or there are multiple values passed in `args`
            dict: if one value was passed through `args` and it matched a known monitor
        
        Example:
            ```python
            import screen_brightness_control as sbc

            # get the information about all monitors
            vcp_info = sbc.windows.VCP.get_display_info()
            print(vcp_info)
            # EG output: [{'name': 'BenQ BNQ78A7', 'model': 'BNQ78A7', ... }, {'name': 'Dell DEL405E', 'model': 'DEL405E', ... }]

            # get information about a monitor with this specific model
            bnq_info = sbc.windows.VCP.get_display_info('BNQ78A7')
            # EG output: {'name': 'BenQ BNQ78A7', 'model': 'BNQ78A7', ... }

            # get information about 2 specific monitors at the same time
            sbc.windows.VCP.get_display_info('DEL405E', 'BNQ78A7')
            # EG output: [{'name': 'Dell DEL405E', 'model': 'DEL405E', ... }, {'name': 'BenQ BNQ78A7', 'model': 'BNQ78A7', ... }]
            ```
        '''
        info = []
        try:
            monitors_enum = win32api.EnumDisplayMonitors()
            monitors = [win32api.GetMonitorInfo(i[0]) for i in monitors_enum]
            monitors = [win32api.EnumDisplayDevices(i['Device'], 0, 1).DeviceID for i in monitors]
            a=0
            for ms in monitors:
                m = ms.split('#')
                serial = m[2]
                model = m[1]

                man_id = model[:3]
                manufacturer = _monitor_brand_lookup(man_id)
                manufacturer = 'Unknown' if manufacturer==None else manufacturer

                tmp = {'name':f'{manufacturer} {model}', 'model':model, 'model_name': None, 'serial':serial, 'manufacturer': manufacturer, 'manufacturer_id': man_id , 'index': a, 'method': VCP}
                info.append(tmp)
                a+=1
        except:
            pass
        if len(args)>0:
            try:
                info = [VCP.filter_displays(i, info) for i in args]
                return info[0] if len(info)==1 else info
            except:
                pass
        return info
Exemple #22
0
 def get(cls, primary=None, device=None):
     monitors = [
         MonitorInfo(win32api.GetMonitorInfo(item[0]))
         for item in win32api.EnumDisplayMonitors(None, None)
     ]
     for monitor in monitors:
         if primary and not monitor.primary: continue
         if device and not monitor.device == device: continue
         return monitor
     return None
 def get_info_for_monitor(self, monitor_ID):
     mon = win32api.EnumDisplayMonitors()
     moninfo = None
     try:
         moninfo = (win32api.GetMonitorInfo(mon[monitor_ID][0]))
         moninfodump = json.dumps(moninfo)
         moninfojsonload = json.loads(moninfodump)
     except:
         print("Monitor ID seems to be like out of the index range")
     return moninfojsonload
Exemple #24
0
def _monitor_hndl_to_screen_n(m_hndl):
    ''' Экраны-мониторы нуменруются от 1. Нулевой экран -- это полный вирутальный. '''
    minfo = win32api.GetMonitorInfo(
        m_hndl
    )  # For example for primary monitor: {'Device': '\\\\.\\DISPLAY1', 'Work': (0, 0, 1920, 1040), 'Flags': 1, 'Monitor': (0, 0, 1920, 1080)}
    screen_n = int(minfo['Device'][len(r'\\.\DISPLAY'):])
    if screen_n <= 0:
        raise FailExit(
            'can not obtaen Screen number from win32api.GetMonitorInfo() = %s'
            % str(minfo))
    return screen_n
def get_wins():
	aray=[]
	num=win32api.GetSystemMetrics(80)
	mlst=win32api.EnumDisplayMonitors(None,None)
	for m in mlst:
		d=win32api.GetMonitorInfo(m[0])
		aray.append((d['Device'],d['Monitor'],m[0]))
	
		#print d['Device'],d['Monitor'],m[0]
	#print 'monitors=%d'%num
	
	return aray
Exemple #26
0
 def calculate_offset(self, *args):
     #GTK returns coordinates as unsigned ints, but win32 can give us negative coordinates!
     self.offset_x = 0
     self.offset_y = 0
     try:
         for m in win32api.EnumDisplayMonitors(None, None):
             mi = win32api.GetMonitorInfo(m[0])
             mx1, my1, _, _ = mi['Monitor']
             self.offset_x = max(self.offset_x, -mx1)
             self.offset_y = max(self.offset_y, -my1)
     except Exception, e:
         log.warn("failed to query monitors: %s", e)
Exemple #27
0
    def on_init(self, controller):
        controller.enable_gesture(Leap.Gesture.TYPE_SWIPE)
        #controller.enable_gesture(Leap.Gesture.TYPE_KEY_TAP)
        controller.config.set("Gesture.Swipe.MinLength", 100.0)
        controller.config.set("Gesture.Swipe.MinVelocity", 160.0)

        #controller.config.set("Gesture.KeyTap.MinDownVelocity", 1.0)
        #controller.config.set("Gesture.KeyTap.HistorySeconds", 1.0)
        #controller.config.set("Gesture.KeyTap.MinDistance", 0.1)

        controller.set_policy(Leap.Controller.POLICY_BACKGROUND_FRAMES)
        controller.config.save()

        self.width = win32api.GetMonitorInfo(win32api.EnumDisplayMonitors(None, None)[0][0])["Monitor"][2]
        self.height = win32api.GetMonitorInfo(win32api.EnumDisplayMonitors(None, None)[0][0])["Monitor"][3]
        print self.width, self.height
        self.xpos = int(self.width / 2)
        self.ypos = int(self.height / 2)


        print "Initialized"
Exemple #28
0
def get_real_display_devices_info():
    """ Return info for real (non-virtual) devices """
    # See Argyll source spectro/dispwin.c MonitorEnumProc, get_displays
    monitors = []
    for monitor in win32api.EnumDisplayMonitors(None, None):
        try:
            moninfo = win32api.GetMonitorInfo(monitor[0])
        except pywintypes.error:
            pass
        else:
            if moninfo and not moninfo["Device"].startswith("\\\\.\\DISPLAYV"):
                monitors.append(moninfo)
    return monitors
Exemple #29
0
 def _monitor_hndl_to_screen_n(self, m_hndl):
     """
     Converts monitor handle to number (from 1)
     0 - virtual monitor
     """
     minfo = win32api.GetMonitorInfo(
         m_hndl)  # For example for primary monitor:
     # {'Device': '\\\\.\\DISPLAY1', 'Work': (0, 0, 1920, 1040), 'Flags': 1, 'Monitor': (0, 0, 1920, 1080)}
     screen_n = int(minfo['Device'][len(r'\\.\DISPLAY'):])
     if screen_n <= 0:
         raise FailExit(
             'can not obtain Screen number from win32api.GetMonitorInfo() = {}'
             .format(minfo))
     return screen_n
Exemple #30
0
def get_workarea_rect():
    '''Get workarea RECT on primary disply'''
    rect = None
    for monitor in win32api.EnumDisplayMonitors():
        monitor_info = win32api.GetMonitorInfo(monitor[0].handle)
        if monitor_info['Flags'] == win32con.MONITORINFOF_PRIMARY:
            rect = monitor_info['Work']
            break
    if rect is None:
        # http://msdn.microsoft.com/en-us/library/windows/desktop/ms632680(v=vs.85).aspx
        w = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
        h = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
        return 0, 0, w, h
    return rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]