Note that there are some explanatory texts on larger screens.

plurals
  1. POC# SendKeys.SendWait to a dialog of another Process (notepad.exe)
    text
    copied!<p>I'm trying to do the following in C#:</p> <ul> <li>Open a new process (notepad.exe)</li> <li>Enter some text (using SendKeys)</li> <li>Close Notepad (deal with any confirmation dialogs)</li> </ul> <p>Here's what I got</p> <pre><code>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 </code></pre> <p>All this works just as expected, but now after I've sent ALT+f+x I get a "Do you want to save changed to Untitled" dialog and I would like to close it from within my applications by "pressing" 'n' for "Don't Save". However</p> <pre><code>SendKeys.SendWait( "n" ); </code></pre> <p>works only if my application has not lost focus (after ALT+f+x). If it did and I try to go back using</p> <pre><code>SetForegroundWindow( p.MainWindowHandle ); </code></pre> <p>this sets the focus to the main notepad window instead of the confirmation dialog. I used the <code>GetForegroundWindow</code> method from user32.dll and found out that the dialog handle is different than the notepad handle (which kinda makes sence) but <code>SetForegroundWindow</code> doesn't work with even with the dialog window handle</p> <p>Any idea how I can give the focus back to the dialog so that I can successfully use <code>SendKeys</code>?</p> <p>here's the full code</p> <pre><code>[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" ); </code></pre> <p>Thank you</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload