Win32api 没有在 python 中使用 GetCursorPos() 给出正确的坐标

Win32api is not giving the correct coordinates with GetCursorPos() in python

当使用 pywin 的 win32api 时,我得到的光标位置值不正确。我的屏幕分辨率是 1920x1080,但是当我使用 GetCursorPos() 时,我在左上角有 (0,0),在右下角有 (1535,863)。我使用的代码如下:

import win32api

def getCursor():
    print win32api.GetCursorPos()

我在 windows 10 上使用 python 2.7 尝试此操作,但我在 windows 8 上的 python 2.6 中也遇到此错误。有什么解决方案吗或解决此问题的方法?

您受 DPI virtualization 约束。您的应用程序尚未声明自己知道高 DPI,并且您的字体缩放比例为 125%。

如果您想避免 DPI 虚拟化,请将高 DPI 感知选项添加到应用程序清单或调用 SetProcessDPIAwareSetProcessDPIAwareness

您可以这样设置感知级别:

import ctypes
awareness = ctypes.c_int()
ctypes.windll.shcore.SetProcessDpiAwareness(2)

意识水平定义如下:

typedef enum _PROCESS_DPI_AWARENESS { 
    PROCESS_DPI_UNAWARE = 0,
    /*  DPI unaware. This app does not scale for DPI changes and is
        always assumed to have a scale factor of 100% (96 DPI). It
        will be automatically scaled by the system on any other DPI
        setting. */

    PROCESS_SYSTEM_DPI_AWARE = 1,
    /*  System DPI aware. This app does not scale for DPI changes.
        It will query for the DPI once and use that value for the
        lifetime of the app. If the DPI changes, the app will not
        adjust to the new DPI value. It will be automatically scaled
        up or down by the system when the DPI changes from the system
        value. */

    PROCESS_PER_MONITOR_DPI_AWARE = 2
    /*  Per monitor DPI aware. This app checks for the DPI when it is
        created and adjusts the scale factor whenever the DPI changes.
        These applications are not automatically scaled by the system. */
} PROCESS_DPI_AWARENESS;

检查这个答案: