Getting a spawned process to stay in focus


  • There are a few similar questions to my problem in the C# and VB forums, but those answers haven't quite gotten me to a solution.  My Framework 2 app creates one of 3 files on user request and then does a Process.Start(filename) to open the file.  I want either the newly opened app to stay in focus or my app to stay in focus.  I don't care which, I just want consistency, and I can't get it.

    The 3 file types are csv, xml, and rtf.  Excel is the typical association for csv and xml files, and it opens them as expected.  (The xml is formatted like an Excel xml "Save As..." export.)  Word is the typical association for rtf and it opens as expected.  If the file type association fails, I explicitly invoke NotePad (csv & xml) or WordPad (rtf) to open the file.

    The problem occurs just after the completed file is opened.  For the xml file, Excel stays in focus as the foreground app.  For the csv and rtf files, the app opens (Word or Excel) and then my application retakes focus.  I've experimented extensively with SetForegroundWindow and SwitchToThisWindow from user32.dll, and found that when the event handler for the user click event is exited, my app always steals focus back... unless it's the xml file.  So I tried to take focus away from Excel for the xml file.  No luck there, either.

    I found a crude way to change the focus back to the file app using a delayed thread to invoke SwitchToThisWindow, and it works (although ugly) for the csv file.  But when the rtf file gets opened by Word, I don't get a process reference to use for the Switch...() call because the pre-existing (but dormant) Word process (created by Outlook) is being reused; Process.Start is not creating a process and therefore doesn't return one.

    I'm at a loss for how to do this.
    • Edited by John Whitmire Thursday, August 06, 2009 7:51 PM clarify
    Thursday, August 06, 2009 7:49 PM


  • OK, it's time to eat crow.  The click event handler finishes with a call to the Focus() method of one of the form's buttons.  Duh!  That causes the form to become the active one and jump to the front (...except for the still-confusing xml file case).  Moving that call to the beginning of the handler, before the call to Process.Start, allows the spawned process to retain focus without a hitch.

    Naturally, I discovered this shortly after finding a nine-out-of-ten solution involving SendKeys in the Form.Activate event.

    The thumping sound you hear is me banging my head against the wall.
    • Marked as answer by John Whitmire Friday, August 07, 2009 6:41 PM
    Friday, August 07, 2009 6:41 PM