模拟按键

时间:2014-01-15 01:19:00

标签: c# console-application

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

1 个答案:

答案 0 :(得分:1)

目前尚不清楚是否要为自己的应用程序或正好在计算机上运行的第三方应用程序/窗口模拟按键操作。我会假设后者。

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

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就是您的朋友。

相关问题