【问题标题】:I want to be able to hold down control by code我希望能够通过代码保持控制
【发布时间】:2014-11-04 00:52:56
【问题描述】:

我正在使用 c#,Visual Studio 2010 用于 Windows 应用程序。

我想按住Ctrl键,过一会再松开。

我试过了,但是没用。

[DllImport("user32.dll")]
    static extern bool keybd_event(byte bVk, byte bScan, uint dwFlags,
    UIntPtr dwExtraInfo);

    public const uint KEYEVENTF_KEYUP = 0x02;
    public const uint VK_CONTROL = 0x11;

// Press the Control key.
keybd_event(VK_CONTROL,0,0,0);
//release the control key
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);

但我得到了这个错误

'ImageR.Form1.keybd_event(byte, byte, uint, System.UIntPtr)的最佳重载方法匹配

无法从“uint”转换为“byte”

无法从“int”转换为“System.UIntPtr”

【问题讨论】:

  • 阅读您所写的内容。您已将函数声明为采用 byte 参数,但随后将 KEYEVENTF_KEYUPVK_CONTROL 声明为类型 uint。正如编译器告诉你的那样,byte != uint。学习阅读错误消息中的实际单词非常重要——它们几乎总是提供信息,如果你只注意它们,你就可以用来找出问题。
  • 另外,keybd_event 已被弃用。请改用SendInput。如果您搜索[c#] SendInput(包括括号),这里有使用它的示例。
  • 将其更改为“public const uint KEYEVENTF_KEYUP = 0x02; public const byte VK_CONTROL = 0x11;”仍然出现错误“无法从 int 转换为 System.UintPtr。
  • [c#] keybd_event 上快速搜索会发现许多使用此过时功能的示例。我仍然强烈建议您停止尝试使用它(同样,它已被弃用)并改为搜索 SendInput 的示例。
  • 我放弃了。 :-) 我只能重复“你应该查看SendInput”这么多次,而且我什至不厌其烦地为你寻找搜索表达式。如果您要忽略收到的回复,您到底为什么要在这里问这个问题?

标签: c# keyboard-hook


【解决方案1】:

我没有找到do SendInput 的任何好的示例,http://www.pinvoke.net/default.aspx/user32.keybd_event 的示例对我不起作用。

解决这个问题的最佳解决方案是http://inputsimulator.codeplex.com/

现在就这么简单:

//Press Ctrl

InputSimulator.SimulateKeyDown(VirtualKeyCode.CONTROL);

//Release Ctrl

InputSimulator.SimulateKeyUp(VirtualKeyCode.CONTROL);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2015-12-23
    • 2014-01-21
    • 2014-09-04
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多