日期:2014-05-17 浏览次数:21188 次
// 声明部分
[StructLayout(LayoutKind.Sequential)]
internal struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Explicit)]
internal struct Input
{
[FieldOffset(0)]
public int type; // Mouse: 0; Keyboard: 1; hardware: 2
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
[DllImport("user32.dll")]
private static extern uint SendInput(uint nInputs, Input[] pInputs, int cbSize);
//使用部分
Input[] input = new Input[T_CartonID.Text.Length * 2 + 4];
int i = 0;
foreach (char nChar in MyText)
{
input[i].type = 1;
input[i].ki.wVk = Convert.ToInt16(nChar);
i++;
input[i].type = 1;
input[i].ki.wVk = Convert.ToInt16(nChar);
input[i].ki.dwFlags = 2;
i++;
}
// Enter key
input[input.Length - 4].type = 1;
input[input.Length - 4].ki.wVk = 0x0D;
input[input.Length - 3].type = 1;
input[input.Length - 3].ki.wVk = 0x0D;
input[input.Length - 3].ki.dwFlags = 2;
input[input.Length - 2].type = 1;
input[input.Length - 2].ki.wVk = 0x0A;
input[input.Length - 1].type = 1;
input[input.Length - 1].ki.wVk = 0x0A;
input[input.Length - 1].ki.dwFlags = 2;
SendInput((uint)input.Length, input, Marshal.SizeOf(input[0]));
------解决方案--------------------
如果向非当前窗体发送,则需要先找到目标窗体的句柄,然后发送对应的消息即可
------解决方案--------------------
可以用API的FindWindow 和 SetForegroundWindow来强制聚焦到其他应用程序上
private void Form1_Load(object sender, EventArgs e)
{
KeyboardHook keyboardHook = new KeyboardHook();//全局按键
keyboardHook.KeyDown += new KeyEventHandler(keyboardHook_KeyDown);
keyboardHook.Start();
}
void keyboardHook_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F2)
{
SendKeys.Send("%A");//发送ALT+A
}
}
------解决方案--------------------
不好意思,SendKeys.Send("%A");//发送ALT+A
A应该是小写,大写不行,写错了。