Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

winapi - How to change cursor image in Python

I want to change my cursor image (everywhere on screen) when my program is running.

I try to load image with win32gui and then use win32api to change cursor image, but something is wrong and my cursor doesn't show up My cursor image is map.cur

import win32api
import time
import win32gui
import win32con

x = win32gui.LoadImage(0,'map.cur',win32con.IMAGE_CURSOR,0,0,win32con.LR_LOADFROMFILE)
win32api.SetCursor(x)

time.sleep(5)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Changing the system cursor is not recommended. For the sake of curiosity, it can be done with SetSystemCursor, example

ctypes.windll.user32.SetSystemCursor(hcursor, 32512) #OCR_NORMAL

See documentation for OCR_NORMAL and other cursor constants.

I would not recommend this at all for python, because it is difficult to restore the cursor, so the user will be stuck with a new cursor unless he changes the cursor through the system settings. You can try to save the old cursor and restore it, but this method fails if your program exits abnormally.

hold = win32gui.LoadImage(0, 32512, win32con.IMAGE_CURSOR, 
                          0, 0, win32con.LR_SHARED )
hsave = ctypes.windll.user32.CopyImage(hold, win32con.IMAGE_CURSOR, 
                                       0, 0, win32con.LR_COPYFROMRESOURCE)
hcursor = win32gui.LoadImage(0, 'file.cur', 
                             win32con.IMAGE_CURSOR, 0, 0, win32con.LR_LOADFROMFILE);
ctypes.windll.user32.SetSystemCursor(hcursor, 32512)
time.sleep(5)

#restore the old cursor
ctypes.windll.user32.SetSystemCursor(hsave, 32512)
  • edited: renamed hnew to hcursor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...