c# - 在任何应用程序中模拟击键

标签 c# winapi keyboard keyboard-hook

如何在不是我的 C# 应用程序的窗口中模拟击键?

现在我正在使用 SendKeys.Send() 但它不起作用。问题是我有一个全局键盘钩子(Hook),所以我直接从键盘捕获输入,SendKeys.Send() 看起来不像真正的键盘敲击。

最好是以这种方式模拟真实的击键,无论我在什么应用程序中,我的程序都会捕捉到它,就像有人按下了一个键一样。

我想我找到了部分问题。这是在按下某个键时调用的事件:

static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
   // Writes the pressed key in the console (it works)
   Console.WriteLine(e.KeyCode.ToString());

   // Check if pressed key is Up Arrow (it works and enters the condition)
   if(e.KeyCode == Keys.Up)
   {
     // Send the key again. (does not work)
     SendKeys.Send("{UP}");
   } 
}

我这样试过:

static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
   // Writes the pressed key in the console (it works)
   Console.WriteLine(e.KeyCode.ToString());

   // Check if pressed key is Up Arrow (it works and enters the condition)
   if(e.KeyCode == Keys.Up)
   {
     // Send the key again. (does not work)
     PostMessage(proc.MainWindowHandle,WM_KEYDOWN, VK_UP,0);
   } 
}

但它也不起作用。问题是因为我在我的事件中发送了键,它会因为按下一个键而调用自己吗?如果有人需要它,上面的代码。

[STAThread]
static void Main(string args)
{
  KeyBoardHook.CreateHook();
  KeyBoardHook.KeyPressed += KeyBoardHook_KeyPressed;
  Application.Run();
  KeyBoardHook.Dispose();
} 

如果您需要 KeyBoardHook 类,我也可以发布。

我的猜测是我的键盘钩子(Hook)正在捕获低级键盘输出,而 SendKeys 只是模拟击键,所以我的钩子(Hook)没有捕获它。有人想出变通办法吗?

最佳答案

我建议您使用这个非常酷的库,它可以为您掩盖所有的复杂性,Windows 输入模拟器可在此处获得:http://inputsimulator.codeplex.com/

我相信它是基于 Windows 的 SendInput function .

关于c# - 在任何应用程序中模拟击键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064512/

相关文章:

ios - 收藏 View 作为自定义键盘不起作用

c++ - 如何将 OpenPrinter 用于网络打印机?

ios - 删除字母大写键盘

c# - 使用较多的 WPF(可选,包括 Silverlight).NET 论坛/讨论站点有哪些?

C# DataGrid 更新所有行

c++ - Windows API全局钩子(Hook)的无限范围

windows - 获取进程桌面

windows - 如何使Right Alt在美国键盘布局中的行为像AltGR?

C#:如何在 xml 注释中引用 default(T) 和构造函数

c# - IDisposable 有什么用?