2

所以我有一个庞大的程序,并决定让其中一种方法在单独的线程中运行。所以我将该方法放在一个单独的类中,并在我的表单上激活它。它似乎就像我想要的那样工作,直到它出现在它给我这个错误的地方:

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

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

谁能告诉我一种不使用 SendKeys 来模拟击键的方法,或者让 SendKeys 在不同的非表单线程中工作的方法?

4

2 回答 2

7

您的控制台应用程序需要一个消息循环。这是通过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
    }
}
于 2012-04-07T19:33:20.387 回答
1

我知道这不是答案,但这是我过去使用 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机器中执行。

于 2015-09-23T15:58:35.873 回答