You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于WshShell对象及PowerShell模拟鼠标滚轮滚动的技术咨询

WshShell SendKeys 与鼠标滚轮模拟说明

一、WshShell SendKeys 不支持鼠标滚轮模拟

WshShell对象的SendKeys方法仅针对键盘按键输入做模拟,没有内置功能直接实现鼠标滚轮滚动。它的设计仅覆盖键盘相关操作(如单键、组合键输入),鼠标类动作(包括滚轮、点击、移动)不在其支持范围内。

二、PowerShell 实现鼠标滚轮滚动的方法

PowerShell本身没有原生命令模拟鼠标滚轮,需调用Windows系统的user32.dll中的API来实现。推荐使用SendInput函数(微软官方推荐的现代输入模拟API),替代已弃用的mouse_event函数。

方法1:使用SendInput API(推荐)

以下脚本定义了可复用的函数,支持自定义滚动方向和幅度:

# 导入Windows API所需类型与函数
Add-Type @"
using System;
using System.Runtime.InteropServices;

public class MouseSimulator {
    [StructLayout(LayoutKind.Sequential)]
    public struct INPUT {
        public int type;
        public MOUSEINPUT mi;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MOUSEINPUT {
        public int dx;
        public int dy;
        public int mouseData;
        public int dwFlags;
        public int time;
        public IntPtr dwExtraInfo;
    }

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);

    public const int INPUT_MOUSE = 0;
    public const int MOUSEEVENTF_WHEEL = 0x0800;
    public const int WHEEL_DELTA = 120; // Windows默认滚轮步长
}
"@

# 模拟鼠标滚轮滚动的函数
function Invoke-MouseWheelScroll {
    param(
        # 滚动参数:正数=向上,负数=向下,数值为WHEEL_DELTA的倍数
        [int]$ScrollAmount = 120
    )

    $inputEvent = New-Object MouseSimulator+INPUT
    $inputEvent.type = [MouseSimulator]::INPUT_MOUSE

    $inputEvent.mi.dx = 0
    $inputEvent.mi.dy = 0
    $inputEvent.mi.mouseData = $ScrollAmount
    $inputEvent.mi.dwFlags = [MouseSimulator]::MOUSEEVENTF_WHEEL
    $inputEvent.mi.time = 0
    $inputEvent.mi.dwExtraInfo = [IntPtr]::Zero

    [MouseSimulator]::SendInput(1, @($inputEvent), [System.Runtime.InteropServices.Marshal]::SizeOf($inputEvent))
}

# 使用示例
Invoke-MouseWheelScroll              # 向上滚动1次(默认幅度)
Invoke-MouseWheelScroll -ScrollAmount -240  # 向下滚动2次

方法2:使用已弃用的mouse_event API

如果仅需简单场景,也可以用旧版的mouse_event函数,但不推荐在生产环境使用:

Add-Type @"
using System.Runtime.InteropServices;
public class MouseSimulator {
    [DllImport("user32.dll")]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, uint dwExtraInfo);
    public const uint MOUSEEVENTF_WHEEL = 0x0800;
    public const int WHEEL_DELTA = 120;
}
"@

# 向上滚动1次
[MouseSimulator]::mouse_event([MouseSimulator]::MOUSEEVENTF_WHEEL, 0, 0, 120, 0)
# 向下滚动1次
[MouseSimulator]::mouse_event([MouseSimulator]::MOUSEEVENTF_WHEEL, 0, 0, 120, 0)

注意:mouse_event已被微软标记为弃用,在多线程或复杂输入场景下可能出现不稳定,优先选择SendInput方案。

内容的提问来源于stack exchange,提问作者Johnny B. Goode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:05:00