【问题标题】:Simulated key press [duplicate]模拟按键[重复]
【发布时间】:2014-01-15 01:19:00
【问题描述】:

我正在尝试制作一个非常简单的程序,我需要模拟按键。我试图找到解决方案,但我的程序似乎不知道任何建议的方法。我不知道这是否是因为我正在使用控制台应用程序或交易是什么,但没有简单的发送虚拟按键的内容,计算机会做出反应,就好像用户自己点击了按钮?

【问题讨论】:

  • 你的问题质量很差。需要更多关于确切您要完成的工作的信息。
  • “模拟按键 c#”为我下载。在 Thejaka Maldeniya 的回答中,我发现我需要使用 System.Windows.Forms。但现在我得到了我回应的错误。我只需要模拟按键。例如,假设我想模拟空格按钮。如果我在 Word 中,它会创建一个空格,如果我在 VLC 中,它会暂停视频,如果我在游戏中,我可能会跳转。

标签: c# console-application


【解决方案1】:

尚不清楚您是想为自己的应用程序模拟按键,还是为碰巧在计算机上运行的第三方应用程序/窗口模拟按键。我假设是后者。

以下最小示例将发送Hello world!notepad 的一个实例,您必须手动启动它。

static void Main(string[] args)
{
    // Get the 'notepad' process.
    var notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
    if (notepad == null)
        throw new Exception("Notepad is not running.");

    // Find its window.
    IntPtr window = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero,
        "Edit", null);

    // Send some string.
    SendMessage(window, WM_SETTEXT, 0, "Hello world!");
}

(full code)

它使用这些 PInvoke 方法和常量:

[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,
    IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg,
    int wParam, string lParam);

private const int WM_SETTEXT = 0x000C;

如果您想了解更多关于如何处理您想要的应用程序、PInvoke 以及向其他应用程序发送消息的信息,Google 是您的朋友。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2013-07-24
    相关资源
    最近更新 更多