尚不清楚您是想为自己的应用程序模拟按键,还是为碰巧在计算机上运行的第三方应用程序/窗口模拟按键。我假设是后者。
以下最小示例将发送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 是您的朋友。