EscribePassword/KeyboardHelper.cs

76 lines
2.2 KiB
C#

using System.Runtime.InteropServices;
using WindowsInput.Native;
using WindowsInput;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
namespace EscribePassword
{
public class KeyboardHelper
{
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
private IntPtr previousWindow;
public void SaveCurrentWindow()
{
previousWindow = GetForegroundWindow();
}
public Rect GetScreenOfPreviousWindow()
{
if (previousWindow != IntPtr.Zero)
{
var rect = new RECT();
if (GetWindowRect(previousWindow, ref rect))
{
return new Rect(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
}
return SystemParameters.WorkArea;
}
public void RestoreAndSimulatePaste(Passwords password)
{
if (previousWindow != IntPtr.Zero)
{
// Restore focus to the previous window
SetForegroundWindow(previousWindow);
var sim = new InputSimulator();
if (password.Usuario != null && password.Usuario.Length > 0)
{
// Simulate typing the username
sim.Keyboard.TextEntry(password.Usuario);
sim.Keyboard.KeyPress(VirtualKeyCode.RETURN);
sim.Keyboard.KeyPress(VirtualKeyCode.TAB);
}
// Simulate typing the password
sim.Keyboard.TextEntry(password.Password);
sim.Keyboard.KeyPress(VirtualKeyCode.RETURN);
sim.Keyboard.KeyPress(VirtualKeyCode.TAB);
}
}
}
}