2

だから私は巨大なプログラムを持っていて、メソッドの1つを別のスレッドで実行する必要があると決めました。そこで、メソッドを別のクラスに配置し、フォームでアクティブ化しました。それが私にこのエラーを与える部分に到達するまで、それは私がそれを望んでいたようにうまくいったようでした:

アプリケーションがWindowsメッセージを処理していないため、SendKeysをこのアプリケーション内で実行することはできません。メッセージを処理するようにアプリケーションを変更するか、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 に答える