如何在非表单应用程序中生成击键

所以我有一个庞大的程序,并决定我应该在一个单独的线程中运行其中一个方法。 所以我把方法放在一个单独的类中,在我的表单上激活它。 它似乎工作正常我想要它,直到它分手它给我这个错误:

SendKeys无法在此应用程序内运行,因为应用程序未处理Windows消息。 更改应用程序以处理消息,或使用SendKeys.SendWait方法。

我试着在线寻找答案。 我想我看到了一些关于SendKeys如何只在Form或其他东西中工作的东西。

任何人都可以告诉我一种不使用SendKeys来模拟击键的方法,或者是一种让SendKeys在不同的非forms线程中工作的方法吗?

您的控制台应用程序需要消息循环。 这是通过Application类完成的。 您需要调用Application.Run(ApplicationContext) 。

class MyApplicationContext : ApplicationContext { [STAThread] static void Main(string[] args) { // Create the MyApplicationContext, that derives from ApplicationContext, // that manages when the application should exit. MyApplicationContext context = new MyApplicationContext(); // Run the application with the specific context. It will exit when // the task completes and calls Exit(). Application.Run(context); } Task backgroundTask; // This is the constructor of the ApplicationContext, we do not want to // block here. private MyApplicationContext() { backgroundTask = Task.Factory.StartNew(BackgroundTask); backgroundTask.ContinueWith(TaskComplete); } // This will allow the Application.Run(context) in the main function to // unblock. private void TaskComplete(Task src) { this.ExitThread(); } //Perform your actual work here. private void BackgroundTask() { //Stuff SendKeys.Send("{RIGHT}"); //More stuff here } } 

我知道这不是一个答案,但这是我过去使用ActiveX和脚本的方式

 Set ws = CreateObject("WScript.Shell") str = "Hi there... ~ Dont click your mouse while i am typing." & _ " ~~This is a send key example, using which you can send your keystrokes" ws.Run("notepad.exe") WScript.Sleep(1000) For c=1 To Len(str) WScript.Sleep(100) 'Increase the value for longer delay ws.SendKeys Mid(str,c,1) Next 

将此代码保存为file.vbs并双击以在Windows机器中执行。