C#模拟实现Union

转自http://www.docin.com/p-46428532.html

在C#中要指定成员的内存布局情况,我们需要结合使用StructLayout Attribute特性、LayoutKind枚举和FiledOffSet Attribute特性,它们都位于System.Runtime.InteropServcies命名空间中。

如果你想将模拟键盘输入发送到指定的位置,可以使用Windows API函数`SetForegroundWindow`和`SendInput`。以下是一个示例代码,它将模拟按下"Hello World"键,并将其发送到指定的文本框中: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; // 设置前台窗口并模拟键盘输入 [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); private const int INPUT_KEYBOARD = 1; private const uint KEYEVENTF_EXTENDEDKEY = 0x0001; private const uint KEYEVENTF_KEYUP = 0x0002; [StructLayout(LayoutKind.Sequential)] private struct INPUT { public int type; public INPUTUNION union; } [StructLayout(LayoutKind.Explicit)] private struct INPUTUNION { [FieldOffset(0)] public KEYBDINPUT keyboardInput; } [StructLayout(LayoutKind.Sequential)] private struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } // 获取窗口句柄 Process process = Process.GetProcessesByName("YourProcessName")[0]; IntPtr hwnd = process.MainWindowHandle; // 设置前台窗口 SetForegroundWindow(hwnd); // 模拟键盘输入 string text = "Hello World"; foreach (char c in text) { INPUT[] inputs = new INPUT[2]; inputs[0].type = INPUT_KEYBOARD; inputs[0].union.keyboardInput.wVk = 0; inputs[0].union.keyboardInput.wScan = (ushort)c; inputs[0].union.keyboardInput.dwFlags = KEYEVENTF_UNICODE; inputs[0].union.keyboardInput.time = 0; inputs[0].union.keyboardInput.dwExtraInfo = IntPtr.Zero; inputs[1].type = INPUT_KEYBOARD; inputs[1].union.keyboardInput.wVk = 0; inputs[1].union.keyboardInput.wScan = (ushort)c; inputs[1].union.keyboardInput.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP; inputs[1].union.keyboardInput.time = 0; inputs[1].union.keyboardInput.dwExtraInfo = IntPtr.Zero; SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT))); } ``` 在代码中,我们首先使用`GetProcessesByName`函数获取指定进程的句柄,然后使用`SetForegroundWindow`函数将其设置为前台窗口。接下来,我们使用`SendInput`函数模拟键盘输入,将每个字符一个接一个地发送到指定的文本框中。你可以根据需要修改代码以适应你的应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值