CaiWuXiTong/scripts/hxb-bank/send-secure-text.ps1

118 lines
3.0 KiB
PowerShell

[CmdletBinding()]
param()
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
if (-not ('CaiwuSecureKeyboard' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class CaiwuSecureKeyboard
{
private const uint INPUT_KEYBOARD = 1;
private const uint KEYEVENTF_KEYUP = 0x0002;
private const ushort VK_SHIFT = 0x10;
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Explicit)]
private struct INPUTUNION
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
}
[StructLayout(LayoutKind.Sequential)]
private struct INPUT
{
public uint type;
public INPUTUNION u;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint count, INPUT[] inputs, int size);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern short VkKeyScan(char character);
private static void SendKey(ushort virtualKey, bool keyUp)
{
INPUT input = new INPUT();
input.type = INPUT_KEYBOARD;
input.u.ki.wVk = virtualKey;
input.u.ki.wScan = 0;
input.u.ki.dwFlags = keyUp ? KEYEVENTF_KEYUP : 0;
if (SendInput(1, new[] { input }, Marshal.SizeOf(typeof(INPUT))) != 1)
{
throw new InvalidOperationException(
"Windows 键盘输入失败,错误码 " + Marshal.GetLastWin32Error()
);
}
}
public static void SendText(string text)
{
foreach (char character in text)
{
short scan = VkKeyScan(character);
if (scan == -1)
{
throw new InvalidOperationException("密码包含无法映射的字符");
}
ushort virtualKey = (ushort)(scan & 0xff);
bool shift = ((scan >> 8) & 0x01) != 0;
if (shift)
{
SendKey(VK_SHIFT, false);
}
SendKey(virtualKey, false);
SendKey(virtualKey, true);
if (shift)
{
SendKey(VK_SHIFT, true);
}
Thread.Sleep(35);
}
}
}
'@
}
$text = [Environment]::GetEnvironmentVariable('CAIWU_SECURE_INPUT', 'Process')
try {
if ([string]::IsNullOrEmpty($text)) {
throw '没有需要发送的文本'
}
[CaiwuSecureKeyboard]::SendText($text)
}
finally {
[Environment]::SetEnvironmentVariable('CAIWU_SECURE_INPUT', $null, 'Process')
}