C#移动鼠标到指定位置并粘贴
时间: 2024-11-14 09:22:20 浏览: 13
在C#中,要模拟移动鼠标到指定位置并粘贴操作,通常需要使用`System.Windows.Forms.Cursor`类以及`SendKeys`函数来触发键盘事件。但是请注意,这通常是用于模拟用户交互,而不是直接在程序内部执行。以下是一个简化的示例,展示如何做到这一点:
```csharp
using System;
using System.Runtime.InteropServices;
public static class MouseAndKeyboardActions
{
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetCursorPos(int x, int y);
public static void MoveMouseToPosition(Point position)
{
SetCursorPos(position.X, position.Y);
}
public static void KeybdEvent(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo)
{
var keybdStruct = new INPUT()
{
Type = InputType.KEYDOWN,
Ki = new KEYBDINPUT()
{
WVirtualKeyCode = bVk,
ScanCode = bScan,
Message = (short)0x40 /* WM_KEYDOWN */,
ExtraInfo = dwExtraInfo,
},
Time = 0,
dwExtraInfo = 0
};
SendInput(1, ref keybdStruct, Marshal.SizeOf(keybdStruct));
}
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint nInputs, IntPtr pInputs, uint cbSize);
public static void PasteClipboardContent()
{
// 确保有剪贴板内容,这里只是一个简单的例子
if (!string.IsNullOrEmpty(System.Windows.Forms.Clipboard.GetText()))
{
KeybdEvent((byte)Keys.V, 0, 0x8000, 0); // 按下V键触发粘贴
KeybdEvent((byte)Keys.VK_RETURN, 0, 0x8000, 0); // 模拟按下Enter键确认粘贴
}
}
}
// 调用示例
Point targetPosition = new Point(x, y);
MouseAndKeyboardActions.MoveMouseToPosition(targetPosition);
MouseAndKeyboardActions.PasteClipboardContent();
```
阅读全文