Powershell使用Windows API拖动鼠标



我有代码应该使用 powershell 进行拖放,我不明白为什么它没有按照我希望的方式工作。详情如下:

function Mouse-signature-import(){
$global:signature=@' 
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@ 
$global:SendMouseClick = Add-Type -memberDefinition $global:signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru 
}
function Mouse-Drag($from1,$from2,$to1,$to2){
Mouse-signature-import
[System.Windows.Forms.Cursor]::Position = "$from1,$from2"
$global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
$global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0); Dont know if I need this because drag is not working in all apps
[System.Windows.Forms.Cursor]::Position = "$to1,$to2"
$global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";
}

我看到鼠标移动并发生拖动,但是我正在使用它来选择文本。在鼠标向上时,文本不再突出显示。我需要调整此代码以防止鼠标向上取消选择我在拖动动作中突出显示的文本。理想情况下,我将在此函数之后使用发送键来执行"^c"以复制我使用此函数的大部分时间。

我添加了这一行,认为它会有所帮助。

$global:SendMouseClick::mouse_event(0x80000000, 0, 0, 0, 0);

=====================溶液:

正如DK所建议的那样,这是时机。我只是在鼠标向上事件之前添加了睡眠时间。

函数鼠标拖动($from 1,$from 2,$to 1,$to 2({ $global:静默鼠标函数 = $true 鼠标签名导入

[System.Windows.Forms.Cursor]::Position = "$from1,$from2"
$global:SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
[System.Windows.Forms.Cursor]::Position = "$to1,$to2"
start-sleep -s 1 # If we do not sleep, then the drag does not work right.
$global:SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
$global:silentMouseFunctions = $false
write-host -f yellow -b black "Mouse-Drag" -nonewline; write-host -f Gray " from " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$from1 $from2" -nonewline;write-host -f Magenta "]" -nonewline; write-host -f Gray " to " -NoNewline; write-host -f Magenta "[" -nonewline; write-host -f Red "$to1 $to2" -nonewline; write-host -f Magenta "]";

在花了一些时间来调试代码之后,我们似乎需要慢慢移动光标才能使拖放正常工作。

下面的代码经过多次测试,用于在桌面上移动图标,它在我的 PC 上运行良好:

Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class Win32 
{
[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
}
"@;
[Win32]::SetCursorPos(25, 25);
[Win32]::mouse_event(0x0002, 0, 0, 0, 0);
for ($i = 0; $i -lt 1000; $i+=100)
{
[Win32]::SetCursorPos($i, $i);
Start-Sleep -m 25
}
[Win32]::mouse_event(0x0004, 0, 0, 0, 0);

最新更新