How to get the text cursor position in Windows? - python

Is it possible to get the overall cursor position in Windows using the standard Python libraries?

Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def queryMousePosition():
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
return { "x": pt.x, "y": pt.y}
pos = queryMousePosition()
print(pos)
I should mention that this code was taken from an example found here
So credit goes to Nullege.com for this solution.

win32gui.GetCursorPos(point)
This retrieves the cursor's position, in screen coordinates - point = (x,y)
flags, hcursor, (x,y) = win32gui.GetCursorInfo()
Retrieves information about the global cursor.
Links:
http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms648390(VS.85).aspx
I am assuming that you would be using python win32 API bindings or pywin32.

You will not find such function in standard Python libraries, while this function is Windows specific. However if you use ActiveState Python, or just install win32api module to standard Python Windows installation you can use:
x, y = win32api.GetCursorPos()

I found a way to do it that doesn't depend on non-standard libraries!
Found this in Tkinter
self.winfo_pointerxy()

Using pyautogui
To install
pip install pyautogui
and to find the location of the mouse pointer
import pyautogui
print(pyautogui.position())
This will give the pixel location to which mouse pointer is at.

For Mac using native library:
import Quartz as q
q.NSEvent.mouseLocation()
#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y
If the Quartz-wrapper is not installed:
python3 -m pip install -U pyobjc-framework-Quartz
(The question specify Windows, but a lot of Mac users come here because of the title)

It's possible, and not even that messy! Just use:
from ctypes import windll, wintypes, byref
def get_cursor_pos():
cursor = wintypes.POINT()
windll.user32.GetCursorPos(byref(cursor))
return (cursor.x, cursor.y)
The answer using pyautogui made me wonder how that module was doing it, so I looked and this is how.

This could be a possible code for your problem :
# Note you need to install PyAutoGUI for it to work
import pyautogui
w = pyautogui.position()
x_mouse = w.x
y_mouse = w.y
print(x_mouse, y_mouse)

Prerequisites
Install Tkinter. I've included the win32api for as a Windows-only solution.
Script
#!/usr/bin/env python
"""Get the current mouse position."""
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
def get_mouse_position():
"""
Get the current position of the mouse.
Returns
-------
dict :
With keys 'x' and 'y'
"""
mouse_position = None
import sys
if sys.platform in ['linux', 'linux2']:
pass
elif sys.platform == 'Windows':
try:
import win32api
except ImportError:
logging.info("win32api not installed")
win32api = None
if win32api is not None:
x, y = win32api.GetCursorPos()
mouse_position = {'x': x, 'y': y}
elif sys.platform == 'Mac':
pass
else:
try:
import Tkinter # Tkinter could be supported by all systems
except ImportError:
logging.info("Tkinter not installed")
Tkinter = None
if Tkinter is not None:
p = Tkinter.Tk()
x, y = p.winfo_pointerxy()
mouse_position = {'x': x, 'y': y}
print("sys.platform={platform} is unknown. Please report."
.format(platform=sys.platform))
print(sys.version)
return mouse_position
print(get_mouse_position())

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()
Or with one-liner from the command line:
python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

I know this is an old thread, but have been having hard time figuring out how to do this with JUST the python standard libraries.
I think the code below will work to get the cursor position in a windows terminal:
import sys
import msvcrt
print('ABCDEF',end='')
sys.stdout.write("\x1b[6n")
sys.stdout.flush()
buffer = bytes()
while msvcrt.kbhit():
buffer += msvcrt.getch()
hex_loc = buffer.decode()
hex_loc = hex_loc.replace('\x1b[','').replace('R','')
token = hex_loc.split(';')
print(f' Row: {token[0]} Col: {token[1]}')

Use pygame
import pygame
mouse_pos = pygame.mouse.get_pos()
This returns the x and y position of the mouse.
See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

If you're doing automation and want to get coordinates of where to click, simplest and shortest approach would be:
import pyautogui
while True:
print(pyautogui.position())
This will track your mouse position and would keep on printing coordinates.

Related

How to play video in tkinter using Python VLC in mac OS?

Can anyone show me a simple code of how to play a video using Python VLC package in mac operating system. I try to configure the sample script in tkvlc.py but it's so hard for me to understand. Please help me so that I can fix the issue on the project that I'm working now.
I want to have a simple code of how to play a video in mac OS using python VLC
Here's the code that I try to configure.
import sys
from ctypes import cdll, c_void_p
from os.path import join
import vlc
from tkinter import *
import tkinter as tk
root = Tk()
instance = vlc.Instance()
p = instance.media_player_new()
'''
FOR windows
'''
# p.set_hwnd(root.winfo_id())
'''
FOR MAC
'''
try:
libtk = 'libtk%s.dylib' % (tk.TkVersion,)
prefix = getattr(sys, 'base_prefix', sys.prefix)
libtk = join(prefix, 'lib', libtk)
dylib = cdll.LoadLibrary(libtk)
# getNSView = dylib.TkMacOSXDrawableView is the
# proper function to call, but that is non-public
# (in Tk source file macosx/TkMacOSXSubwindows.c)
# and dylib.TkMacOSXGetRootControl happens to call
# dylib.TkMacOSXDrawableView and return the NSView
_GetNSView = dylib.TkMacOSXGetRootControl
# C signature: void *_GetNSView(void *drawable) to get
# the Cocoa/Obj-C NSWindow.contentView attribute, the
# drawable NSView object of the (drawable) NSWindow
_GetNSView.restype = c_void_p
_GetNSView.argtypes = c_void_p,
del dylib
except (NameError, OSError): # image or symbol not found
def _GetNSView(unused):
return None
libtk = "N/A"
h = root.winfo_id() # .winfo_visualid()?
# XXX 1) using the videopanel.winfo_id() handle
# causes the video to play in the entire panel on
# macOS, covering the buttons, sliders, etc.
# XXX 2) .winfo_id() to return NSView on macOS?
v = _GetNSView(h)
if v:
p.set_nsobject(v)
else:
p.set_xwindow(h) # plays audio, no video
p.set_media(instance.media_new('1.mp4'))
p.play()
root.mainloop()
Here's the error :
[00007fc07bb3c6f0] main video output error: video output creation failed
[00007fc07d87c5e0] main decoder error: failed to create video output
[00007fc07d87c5e0] videotoolbox decoder: vt cvpx chroma: 420v
[00007fc07b7bdc70] macosx vout display error: No drawable-nsobject nor vout_window_t found, passing

Python console Fullscreen? Maybe using os.system?

I'm trying to figure out how to get my program to open in a fullscreen console window.
Is there any command that you can type within the command prompt to toggle fullscreen?
If so I'd imagine the code going something like:
from os import system
system("toggle.fullscreen")
{CODE HERE}
I understand mode con can be used, but that doesn't actually toggle it being maximized, which would be much more useful for me, thanks!
Here's a function to maximize the current console window. It uses ctypes to call WinAPI functions. First it calls GetLargestConsoleWindowSize in order to figure how big it can make the window, with the option to specify a number of lines that exceeds this in order to get a scrollback buffer. To do the work of resizing the screen buffer it simply calls mode.com via subprocess.check_call. Finally, it gets the console window handle via GetConsoleWindow and calls ShowWindow to maximize it.
import os
import ctypes
import msvcrt
import subprocess
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
user32 = ctypes.WinDLL('user32', use_last_error=True)
SW_MAXIMIZE = 3
kernel32.GetConsoleWindow.restype = wintypes.HWND
kernel32.GetLargestConsoleWindowSize.restype = wintypes._COORD
kernel32.GetLargestConsoleWindowSize.argtypes = (wintypes.HANDLE,)
user32.ShowWindow.argtypes = (wintypes.HWND, ctypes.c_int)
def maximize_console(lines=None):
fd = os.open('CONOUT$', os.O_RDWR)
try:
hCon = msvcrt.get_osfhandle(fd)
max_size = kernel32.GetLargestConsoleWindowSize(hCon)
if max_size.X == 0 and max_size.Y == 0:
raise ctypes.WinError(ctypes.get_last_error())
finally:
os.close(fd)
cols = max_size.X
hWnd = kernel32.GetConsoleWindow()
if cols and hWnd:
if lines is None:
lines = max_size.Y
else:
lines = max(min(lines, 9999), max_size.Y)
subprocess.check_call('mode.com con cols={} lines={}'.format(
cols, lines))
user32.ShowWindow(hWnd, SW_MAXIMIZE)
You can use keyboard.press. Install with pip3 install keyboard if it is not installed.
Code:
import keyboard
keyboard.press('f11')
I found this awhile back on a different post and it works perfectly for console window maximization:
import win32gui, win32con
hwnd = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)

How to make a messagebox auto close in several seconds by Python?

I already know how to make a Messagebox by Python:
import ctypes
ctypes.windll.user32.MessageBoxW(0, 'test', "Reminding", 0)
However, I want it to be closed by itself in several seconds after it shows up.
Is there any method to realize it?
Psuedo code:
def AutoCloseMessageBoxW(text, title, close_until_seconds)
I have found a lot of methods to realize this by other language such as C# and Java.
But I just can't find any method to realize it by Python.
import ctypes
import threading
import time
#ctypes.windll.user32.MessageBoxA(0, 'test', "Reminding", 0)
def worker(title,close_until_seconds):
time.sleep(close_until_seconds)
wd=ctypes.windll.user32.FindWindowA(0,title)
ctypes.windll.user32.SendMessageA(wd,0x0010,0,0)
return
def AutoCloseMessageBoxW(text, title, close_until_seconds):
t = threading.Thread(target=worker,args=(title,close_until_seconds))
t.start()
ctypes.windll.user32.MessageBoxA(0, text, title, 0)
AutoCloseMessageBoxW('112','TEST_CLOSE',3)
Use pyautogui
import pyautogui as py # pip install pyautogui
# It is automatically terminated after three seconds. If automatically ends, return "Timeout" returns.
def show_message():
res = py.confirm(text='Message...', buttons=['Yes', 'No'], timeout=3000)
print(res)

Prevent OS X from going to sleep with Python?

Is there a way to prevent a computer running OS X from going to sleep from within a Python script?
You can use the built-in caffeinate command.
subprocess.Popen('caffeinate')
This is how I use it:
import sys
import subprocess
if 'darwin' in sys.platform:
print('Running \'caffeinate\' on MacOSX to prevent the system from sleeping')
subprocess.Popen('caffeinate')
You can also run caffeinate in an external terminal window and leave it open to achieve what the OP wants.
open a terminal
type caffeinate
press Enter
Once you have done this, your Mac will stay awake for as long as you leave the Terminal running.
You can minimize or hide it, and your Mac will not go to sleep until you use the keyboard shortcut Ctrl+C to interrupt the command.
source
Since OS 10.6, you have to make use of the IOPMAssertion family of functions, available in Cocoa. This is really well explained there.
Then, you will have to call it from Python. I'm not sure that there're already specific bindings for Cocoa in Python, but you can call Objective-C functions. It is really well described here.
There is a Python utility that illustrates how to raise the required assertions in Python directly: https://github.com/minrk/appnope
Another alternative would be to run the below script with
python <location/of/my/script.py> <hour until I want the PC to be awake>
e.g.
python /Users/johndee/Downloads/keep_awake.py 18:30
The script, which is to be saved locally:
#!/usr/bin/env python3
import random
import sys
import time
from datetime import datetime
from tkinter import Tk
import pyautogui
CHECK_STATUS_ONCE_IN = 120
WAIT_FOR_POSITION_CHANGE = 10
def current_position():
tkinter = Tk()
return [tkinter.winfo_pointerx(), tkinter.winfo_pointery()]
def mouse_is_moving():
pos1 = current_position()
time.sleep(WAIT_FOR_POSITION_CHANGE)
pos2 = current_position()
return not pos1 == pos2
def keep_awake():
# Shake the mouse a lil bit
initial_x, initial_y = current_position()
try:
for _ in range(random.randint(1, 10)):
# Mouse
pyautogui.moveTo(random.randint(1, 1000), random.randint(1, 1000))
# Keys
pyautogui.press("shift")
# Restore controls
pyautogui.moveTo(initial_x, initial_y)
except pyautogui.FailSafeException as e:
print(e)
def inspect_activity_until(time_to_stop: datetime):
time_to_stop = datetime.now().replace(
hour=time_to_stop.hour, minute=time_to_stop.minute
)
while datetime.now() < time_to_stop:
if not mouse_is_moving():
keep_awake()
time.sleep(CHECK_STATUS_ONCE_IN)
print(f"Stopping at {datetime.now()}")
if __name__ == "__main__":
given_time = sys.argv[1]
date_time_obj = datetime.strptime(given_time, "%H:%M")
inspect_activity_until(date_time_obj)

disable or lock mouse and keyboard in Python?

Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard.
I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want:
import pythoncom, pyHook
def uMad(event):
return False
hm = pyHook.HookManager()
hm.MouseAll = uMad
hm.KeyAll = uMad
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
I have extended Fábio Diniz's answer to a class which provides both a block() and an unblock() function which block (selectively) mouse/keyboard inputs. I also added a timeout functionality which (hopefully) addresses the annoyance of locking oneself out.
import pyHook
from threading import Timer
import win32gui
import logging
class blockInput():
def OnKeyboardEvent(self,event):
return False
def OnMouseEvent(self,event):
return False
def unblock(self):
logging.info(" -- Unblock!")
if self.t.is_alive():
self.t.cancel()
try: self.hm.UnhookKeyboard()
except: pass
try: self.hm.UnhookMouse()
except: pass
def block(self, timeout = 10, keyboard = True, mouse = True):
self.t = Timer(timeout, self.unblock)
self.t.start()
logging.info(" -- Block!")
if mouse:
self.hm.MouseAll = self.OnMouseEvent
self.hm.HookMouse()
if keyboard:
self.hm.KeyAll = self.OnKeyboardEvent
self.hm.HookKeyboard()
win32gui.PumpWaitingMessages()
def __init__(self):
self.hm = pyHook.HookManager()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
block = blockInput()
block.block()
import time
t0 = time.time()
while time.time() - t0 < 10:
time.sleep(1)
print(time.time() - t0)
block.unblock()
logging.info("Done.")
You can have a look at the main routine for example usage.
For me, just two lines of programming solved the problem:
from ctypes import *
ok = windll.user32.BlockInput(True) #enable block
#or
ok = windll.user32.BlockInput(False) #disable block
Totally different take since all the solutions mentioned above use a quiet outdated library(pyhook) and this pyhook method personally didnt work for me.
import keyboard
from pynput.mouse import Controller
from time import sleep
def blockinput():
global block_input_flag
block_input_flag = 1
t1 = threading.Thread(target=blockinput_start)
t1.start()
print("[SUCCESS] Input blocked!")
def unblockinput():
blockinput_stop()
print("[SUCCESS] Input unblocked!")
def blockinput_start():
mouse = Controller()
global block_input_flag
for i in range(150):
keyboard.block_key(i)
while block_input_flag == 1:
mouse.position = (0, 0)
def blockinput_stop():
global block_input_flag
for i in range(150):
keyboard.unblock_key(i)
block_input_flag = 0
blockinput()
print("now blocking")
sleep(5)
print("now unblocking")
I just slightly modified the #Robert code and instead of the time I used external interrupt to close the program i.e. if you connect any external drive then the program gets close and your mouse and keyboard will be working perfectly.
import pyHook
from threading import Timer
import win32gui
import logging
import win32file
def locate_usb():#this will check any external Drives
drive_list = []
drivebits = win32file.GetLogicalDrives()
# print(drivebits)
for d in range(1, 26):
mask = 1 << d
if drivebits & mask:
# here if the drive is at least there
drname = '%c:\\' % chr(ord('A') + d)
t = win32file.GetDriveType(drname)
if t == win32file.DRIVE_REMOVABLE:
drive_list.append(drname)
return drive_list
class blockInput():
def OnKeyboardEvent(self,event):
return False
def OnMouseEvent(self,event):
return False
def unblock(self):
try: self.hm.UnhookKeyboard()
except: pass
try: self.hm.UnhookMouse()
except: pass
def block(self ,keyboard = True, mouse = True):
while(1):
if mouse:
self.hm.MouseAll = self.OnMouseEvent
self.hm.HookMouse()
if keyboard:
self.hm.KeyAll = self.OnKeyboardEvent
self.hm.HookKeyboard()
win32gui.PumpWaitingMessages()
cg= locate_usb()
if cg:
break
def __init__(self):
self.hm = pyHook.HookManager()
if __name__ == '__main__':
block = blockInput()
block.block()
block.unblock()
I hope this code will help you
Since 2018, you can now use pynput (v1.4+) to suppress keyboard and mouse events on Windows, Mac, and Linux.
import pynput
# Disable mouse and keyboard events
mouse_listener = pynput.mouse.Listener(suppress=True)
mouse_listener.start()
keyboard_listener = pynput.keyboard.Listener(suppress=True)
keyboard_listener.start()
# Enable mouse and keyboard events
mouse_listener.stop()
keyboard_listener.stop()
This also disables mouse scrolling and clicking.
However, this does not stop users from pressing Ctrl+Alt+Del on Windows. But you can run the script in an elevated command prompt, and the mouse and keyboard will still be disabled, even if they opened Task Manager using Ctrl+Alt+Delete, so there is no harm done (apparently there are way to actually prevent Ctrl+Alt+Delete, but do your own research for that)
You can use pyautogui to do this. Though I recommend adding keyboard for making a stopping key. First, you want to install pyautogui and keyboard.
Please note: this only disables the mouse not the keyboard, that is a very bad idea.
pip install pyautogui
pip install keyboard
Ok, with that sorted, we have to actually make the disabler.
import pyautogui
import keyboard
stopKey = "s" #The stopKey is the button to press to stop. you can also do a shortcut like ctrl+s
maxX, maxY = pyautogui.size() #get max size of screen
While True:
if keyboard.is_pressed(stopKey):
break
else:
pyautogui.moveTo(maxX/2, maxY/2) #move the mouse to the center of the screen
Ok, but there is 2 ways to get out of this. pressing S, and also quickly moving the mouse to one of the corners of the screen (that is a pyautogui failsafe, but we can disable that). If you want to disable the failsafe, add this after the imports:
pyautogui.FAILSAFE = False
Please note that disabling the failsafe is NOT recommended!
Ok, so now the only way to exit is the S key. If you want to stop this somewhere else in your program, do this:
pyautogui.press(stopKey)
Ok, so its not perfect, but it will stop you from doing basically anything with your mouse.

Categories

Resources