屏幕坐标转窗口坐标 - ScreenToClient
函数简介
将屏幕坐标转换为窗口客户区坐标。该函数用于将相对于屏幕左上角的绝对坐标转换为相对于窗口客户区左上角的相对坐标。这在处理全局鼠标事件、拖放操作等需要将屏幕坐标转换为窗口内部坐标的场景中非常有用。
接口名称
ScreenToClient
DLL调用
int ScreenToClient(long ola, long hwnd, int* x, int* y)
参数定义:
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。hwnd
(长整型数): 目标窗口的句柄。x
(整型数指针): 传入屏幕X坐标,返回对应的客户区X坐标。y
(整型数指针): 传入屏幕Y坐标,返回对应的客户区Y坐标。
示例:
// 获取当前鼠标位置并转换为窗口客户区坐标
int x, y;
GetCursorPos(&x, &y);
int ret = ScreenToClient(ola, hwnd, &x, &y);
if (ret == 1) {
printf("鼠标在客户区的位置:(%d, %d)\n", x, y);
} else {
printf("坐标转换失败\n");
}
// 判断鼠标是否在客户区内
int x1, y1, x2, y2;
GetClientRect(ola, hwnd, &x1, &y1, &x2, &y2);
if (x >= 0 && x <= x2 && y >= 0 && y <= y2) {
printf("鼠标在客户区内\n");
} else {
printf("鼠标在客户区外\n");
}
// 将屏幕上的一个矩形区域转换为客户区坐标
int rect_left = 100, rect_top = 100;
int rect_right = 200, rect_bottom = 200;
ret = ScreenToClient(ola, hwnd, &rect_left, &rect_top);
ret &= ScreenToClient(ola, hwnd, &rect_right, &rect_bottom);
if (ret == 1) {
printf("矩形在客户区的位置:左上(%d, %d), 右下(%d, %d)\n",
rect_left, rect_top, rect_right, rect_bottom);
}
COM调用
int ScreenToClient(long hwnd, int* x, int* y)
参数定义:
hwnd
(长整型数): 目标窗口的句柄。x
(整型数指针): 传入屏幕X坐标,返回对应的客户区X坐标。y
(整型数指针): 传入屏幕Y坐标,返回对应的客户区Y坐标。
示例:
# 获取当前鼠标位置并转换为窗口客户区坐标
import win32api
x, y = win32api.GetCursorPos()
ret = ola.ScreenToClient(hwnd, x, y)
if ret == 1:
messagebox(f"鼠标在客户区的位置:({x}, {y})")
else:
messagebox("坐标转换失败")
# 判断鼠标是否在客户区内
x1, y1, x2, y2 = 0, 0, 0, 0
ola.GetClientRect(hwnd, x1, y1, x2, y2)
if x >= 0 and x <= x2 and y >= 0 and y <= y2:
messagebox("鼠标在客户区内")
else:
messagebox("鼠标在客户区外")
# 将屏幕上的一个矩形区域转换为客户区坐标
rect_left = rect_top = 100
rect_right = rect_bottom = 200
ret = ola.ScreenToClient(hwnd, rect_left, rect_top)
ret &= ola.ScreenToClient(hwnd, rect_right, rect_bottom)
if ret == 1:
messagebox(f"矩形在客户区的位置:左上({rect_left}, {rect_top}), "
f"右下({rect_right}, {rect_bottom})")
返回值
整型数:
- 0: 转换失败
- 1: 转换成功
注意事项
- 窗口必须处于可见状态,否则坐标转换可能失败
- 传入的坐标是相对于屏幕左上角的绝对坐标
- 返回的坐标是相对于客户区左上角的相对坐标,可能为负值(表示点在客户区外)
- 如果需要将客户区坐标转换为屏幕坐标,请使用 ClientToScreen 函数
- 在处理拖放操作时,通常需要使用此函数将屏幕坐标转换为客户区坐标