Skip to content

Commit 5ba2b13

Browse files
committed
优化锁屏时鼠标的移动方式
1 parent 74d208e commit 5ba2b13

File tree

2 files changed

+32
-10
lines changed

2 files changed

+32
-10
lines changed

src/ComputerLock/Platforms/MouseHook.cs

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
using System.Runtime.InteropServices;
2-
3-
namespace ComputerLock.Platforms;
1+
namespace ComputerLock.Platforms;
42
internal class MouseHook : WindowsInputHook
53
{
6-
private int _cursorCount = 0;
7-
private Random _random = new Random();
4+
private int _cursorCount;
5+
private readonly Random _random = new();
86
private bool _isAutoInput;
97
protected override int HookType => WinApi.WH_MOUSE_LL;
108

@@ -65,12 +63,25 @@ public void ResetCursorState()
6563
public void MoveAndClick()
6664
{
6765
_isAutoInput = true;
68-
var x = _random.Next(0, 100);
69-
var y = _random.Next(0, 100);
66+
if (!WinApi.GetCursorPos(out var current))
67+
{
68+
_isAutoInput = false;
69+
return;
70+
}
71+
72+
// 生成一个很小的偏移量,避免明显跳动
73+
var dx = _random.Next(-2, 3);
74+
var dy = _random.Next(-2, 3);
75+
if (dx == 0 && dy == 0)
76+
{
77+
dx = 1;
78+
}
79+
80+
var targetX = current.X + dx;
81+
var targetY = current.Y + dy;
7082

71-
var p = new Point(x, y);
72-
WinApi.SetCursorPos((int)p.X, (int)p.Y);
73-
WinApi.mouse_event(WinApi.MOUSEEVENTF_RIGHTDOWN | WinApi.MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
83+
WinApi.SetCursorPos(targetX, targetY);
84+
WinApi.mouse_event(WinApi.MOUSEEVENTF_RIGHTDOWN | WinApi.MOUSEEVENTF_RIGHTUP, targetX, targetY, 0, 0);
7485
_isAutoInput = false;
7586
}
7687

src/ComputerLock/Platforms/WinApi.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ internal static class WinApi
4040
[DllImport("user32.dll")]
4141
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
4242

43+
[StructLayout(LayoutKind.Sequential)]
44+
public struct POINT
45+
{
46+
public int X;
47+
public int Y;
48+
}
49+
50+
[DllImport("user32.dll")]
51+
[return: MarshalAs(UnmanagedType.Bool)]
52+
public static extern bool GetCursorPos(out POINT lpPoint);
53+
4354
#endregion
4455

4556
#region 键盘相关

0 commit comments

Comments
 (0)