2012-04-07 8 views
0

私は巨大なプログラムを持っており、メソッドの1つを別のスレッドで実行する必要があると判断しました。だから私は別のクラスにメソッドを置く、私のフォーム上でそれをアクティブにします。ノンフォームアプリケーションでキーストロークを生成する方法

SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method.

私は答えをオンラインで探してみました。私はSendKeysがFormや何かの中でしか動作しないことについて何かを見たと思う。

SendKeysを使用せずにキーストロークをシミュレートする方法や、SendKeysを別の非フォームスレッドで動作させる方法を教えてもらえますか?

+0

ソースを表示してください...正確に何を試しましたか? – Yahia

+0

ちょうどそれはこのように行くふりをします。 public class example() { Sendkeys.Send( "{RIGHT}"); } しかし、それは私が得るエラーのために動作しません。 –

+1

@ user1219649私たちの代わりに、あなたが現在やっていることをお見せしてください。もっと便利な答えが得られます –

答えて

5

コンソールアプリケーションにメッセージループが必要です。これは、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 
    } 
} 
+0

上記のコードは、実際には私にいくつかのエラーを与えました。 「this.Exit()」はExit()が存在しないために機能しません。また、私のメインフォームからクラスを呼び出そうとすると、「クラスが保護レベルのためにアクセスできない」というエラーが表示されます。どんな助け? –

+0

This.Exitは動作しませんでした。これは、クラスをApplicationContextから継承することを忘れている可能性があるためです。アクセシビリティレベルはプライベートコンストラクタを持つためです。しかし、フォームからこのコードを使用しているのであれば、それは統制されていないはずです。これは、コンソールアプリケーションでメッセージループを取得するためのものです。フォームアプリケーションの場合、BackgroundWorkerを使用してsendkeysコードをそこに置きます。 –

+0

私はタイプミスがあったと思います。それは 'this.ExitThread()'でなければなりません。 –

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、ダブルクリックとしてこのコードを保存します。

関連する問題