私は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" );
ありがとうございました