发送按键的问题

a78205917 2010-03-24 12:14:10
如何向一个不是当前窗口的窗体发送按键啊,比如发送个alt+a过去,如何实现啊,研究了好久都以失败告终,有没有高手能帮帮小弟的。
...全文
98 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
事理 2010-03-24
  • 打赏
  • 举报
回复
可以用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
}
}
Python 2010-03-24
  • 打赏
  • 举报
回复
如果向非当前窗体发送,则需要先找到目标窗体的句柄,然后发送对应的消息即可
Python 2010-03-24
  • 打赏
  • 举报
回复

// 声明部分
[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]));
yingzhilian2008 2010-03-24
  • 打赏
  • 举报
回复
键盘钩子 !!!
事理 2010-03-24
  • 打赏
  • 举报
回复
不好意思,SendKeys.Send("%A");//发送ALT+A
A应该是小写,大写不行,写错了。
  • 打赏
  • 举报
回复
能取名叫Python。膜拜啊
[Quote=引用 2 楼 python 的回复:]
如果向非当前窗体发送,则需要先找到目标窗体的句柄,然后发送对应的消息即可
[/Quote]

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧