2

私はC#で次のことをしようとしています:

  • 新しいプロセス (notepad.exe) を開きます
  • テキストを入力します (SendKeys を使用)
  • メモ帳を閉じる (確認ダイアログを処理する)

これが私が得たものです

Process p = new Process();
p.StartInfo.Filename = "notepad.exe";
p.Start();

// use the user32.dll SetForegroundWindow method
SetForegroundWindow( p.MainWindowHandle ); // make sure notepad has focus

SendKeys.SendWait( "some text" );

SendKeys.SendWait( "%f" ); // send ALT+f
SendKeys.SendWait( "x" ); // send x = exit

// a confirmation dialog appears

これはすべて期待どおりに機能しますが、ALT + f + x を送信した後、「無題に変更を保存しますか」というダイアログが表示され、「n」を押してアプリケーション内から閉じたいと思います。 '「保存しない」の場合。でも

SendKeys.SendWait( "n" ); 

アプリケーションがフォーカスを失っていない場合にのみ機能します(ALT + f + xの後)。もしそうなら、私は使用して戻ろうとします

SetForegroundWindow( p.MainWindowHandle );

これにより、確認ダイアログではなく、メモ帳のメイン ウィンドウにフォーカスが設定されます。user32.dllのメソッドを使用GetForegroundWindowしたところ、ダイアログ ハンドルがメモ帳のハンドルとは異なることがわかりました (これはちょっと理にかなっています) がSetForegroundWindow、ダイアログ ウィンドウのハンドルでも機能しません。

正常に使用できるように、フォーカスをダイアログに戻す方法はありますSendKeysか?

ここに完全なコードがあります

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);        

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();             

[DllImport("User32.DLL")] 
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 

public const int SW_RESTORE = 9;        

    ...

Process p = new Process();
p.StartInfo.FileName = "notepad.exe";
p.Start();
Thread.Sleep( 1000 );

SendKeys.SendWait( "some text" );
SendKeys.SendWait( "%f" ); // send ALT+F
SendKeys.SendWait( "x" ); // send x = exit

IntPtr dialogHandle = GetForegroundWindow();
System.Diagnostics.Trace.WriteLine( "notepad handle: " + p.MainWindowHandle );
System.Diagnostics.Trace.WriteLine( "dialog handle: " + dialogHandle );

Thread.Sleep( 5000 ); // switch to a different application to lose focus

SetForegroundWindow( p.MainWindowHandle );
ShowWindow( dialogHandle, SW_RESTORE );

Thread.Sleep( 1000 );
SendKeys.SendWait( "n" );

ありがとうございました

4

1 に答える 1

2

持っていないものを与えることはできませんSetForegroundWindow()。アプリケーションに現在フォーカスがある場合にのみ機能します。

最新の Windows バージョンでは、アプリケーションがフォーカスを盗むのを防ぎます。これは、Windows 9x の時代には大きな問題でした。

また、'Alt+F, x' は、英語の Windows バージョンでの終了のみを指し、他のほとんどの言語では機能しません。の使用は避けてくださいSendKeys()。信頼できる方法で使用することは不可能です。

于 2012-02-17T10:05:15.557 に答える